A boolean expression that checks if a previously declared variable sum was not equal to 3.14

I am working on previous exam papers, trying to create my own Java experience. There are two answers to this question. The first is my own, which seems straightforward, and the second is my lecturer, which seems incomprehensible to me at this stage in the development of Java.

Here is my code:

public class InClassTestTwoQ2 { public static void main(String[] args){ double sum = 3.14; System.out.println(test(sum)); System.out.println(testTwo(sum)); } public static boolean test(double sum){ return sum != 3.14; //My boolean test return type } public static boolean testTwo(double sum){ return Math.abs(sum - 3.14) > 1e-14; //Lecturer boolean test return type } } 

Does Math.abs use the best option here? Also, I'm not sure what 1e-14 does? Can someone explain any possibilities as to why my lecturer returned his logical expression in this way? Mine seems straightforward, where would I never do it my own way?

Also, please forgive any errors in my code. I am still learning Java. Thank you very much.

+4
source share
2 answers

To give you an overview of why your lecturer answers better, while your answer is not as simple as you think, consider the following:

3.1444440 and 3.1444441

Are they equal? Well, in Java, if you compare them simply with == , then you get false . This is why you should never compare double / float types with == . The best way to compare floating types is to use tolerance value . You want to verify that the result of the subtraction of the two floating-point types is WITHIN, which is the tolerance value. For example, the tolerance value your teacher used is 1e-14 . Therefore, if sum-3.14 is within the acceptable range, then two numbers are considered equal.

Also note that Math.abs gives you an absolute subtraction value, so you will never get a negative number, otherwise you will not get the correct result.

Hope this gives you an overview.

+2
source

What your instructor posted is using epsilon floating point usage, which in your case is 1.0e14 (see link):

http://en.wikipedia.org/wiki/Machine_epsilon

As to why you want to use this, and why it is better - refer to this link:

http://www.ibm.com/developerworks/java/library/j-jtp0114/

What are the conditions:

"If you don’t know the scale of the basic measurements, use the test" abs (a / b - 1) <epsilon "is likely to be more reliable than just comparing the difference."

It should be noted that all platforms and languages ​​must deal with floating point comparisons at a certain level. Although this conversation does not apply to your language (it is in C ++), some of the points made in this discussion also apply to Java.

What is the most efficient way for floating and double comparing?

+2
source

All Articles