1.0
and 2.0
are double
s.
Arithmetic between double
s and float
s will implicitly convert the float
s to doubles
.
You need to force the entire expression to use float
s by adding the f
suffix to all of your literals.
Question
I was looking at a simple way to approximate Machine Epsilon in Java:
float machEps = 1.0f;
do
machEps /= 2.0f;
while ((float) (1.0 + (machEps / 2.0)) != 1.0);
System.out.println( machEps);
This returns:
1.1920929E-7
However, when I remove the conversion to float
in the while
loop:
float machEps = 1.0f;
do
machEps /= 2.0f;
while ( (1.0 + (machEps / 2.0)) != 1.0);
System.out.println( machEps);
I get:
2.220446E-16
I'm not quite sure why this is....my guess is that in the second case Java attempts to expand machEps
from a float
to a double
. However, I'm not sure if that is an accurate statement or if there is another reason why I get two different answers.
Solution
1.0
and 2.0
are double
s.
Arithmetic between double
s and float
s will implicitly convert the float
s to doubles
.
You need to force the entire expression to use float
s by adding the f
suffix to all of your literals.
OTHER TIPS
Are you looking for java.lang.Math.ulp
?
Returns the size of an ulp of the argument. An ulp of a double value is the positive distance between this floating-point value and the double value next larger in magnitude.
You can easily find the smallest float that is strictly greater than 1.0 using Math.nextUp(1.0f).