Confusing return statement
-
03-07-2019 - |
Question
I'm failing to understand exactly what the IF statement is doing, from what I can see it is checking if the variable x
is equal to the int 0
. If this is true
the ABSOLUTE value of the variable y
is returned... this is when I lose the plot, why would the return statement then go on to include <= ESPILON
? Surely this means less than or equal to the value of epsilon? if so how is that working? If it doesn't mean that then what does it mean?
(JAVA CODE)
final double EPSILON = 1E-14;
if (x == 0)
return Math.abs(y) <= EPSILON;
Solution
Floating-point math is by its nature inaccurate, so rather than testing for equivalence (which is always a bad idea), instead the developer has chosen a small number (1x10^-14 in this case) as the acceptable tolerance for proximity to zero. The return statement returns a comparison, so what this will do is take the absolute value of y, and return true if and only if it is sufficiently close to zero, where sufficiently close is defined by EPSILON.
OTHER TIPS
It returns true if the absolute value of y is <= EPSILON, and false otherwise. The <= is evaluated before the return statement. This code is equivalent:
if(x == 0)
{
boolean ret = Math.abs(y) <= EPSILON;
return ret;
}
The code isn't simply read from left to right. A simpler example is
int x = 3 + 4 * 5;
After evaluating this, x is 23, not 35. The evaluation is 3 + (4*5), not (3+4)*5, because the * has a higher precedence than the +. The return statement in the original example has a very low precedence. All operators like +, -, <, >= are evaluated before it.
The entire expression
Math.abs(y) <= EPSILON
should be evaluated first, which means the function is going to return a boolean value (true/false). Having said that, if
x != 0
then I'm not sure what will get returned.
You're right that it is checking if the variable x is equal to (well, maybe int) 0. However, if this is true then it doesn't return the absolute value of y, it returns a boolean, the result of the <= operator.
It's returning a boolean value.
Epsilon is a double, holding the value 1E-14.
This is the actual IF statement
if (x==0) {
return MATH.abs(y) <= EPSILON;
}
So, what's getting returned is if the absolute value of y is less than or equals to Epsilon.
I haven't done Java in a long time but it would appear that this is actually returning a boolean (which might be implicitly cast).
I would say that if x equals 0, it returns true when the absolute value of y <= Epsilon, otherwise it returns false.
However if x doesn't equal 0 then it would return null, as no statement covers the else.
It is equivalent to this
return (Math.abs(y) <= EPSILON);
which should have been added to the code for clarity. As has been mentioned, it returns a boolean.
An alternatives would be
if (Math.abs(y) <= EPSILON)
return true;
else
return false;