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.

Était-ce utile?

La solution

1.0 and 2.0 are doubles.

Arithmetic between doubles and floats will implicitly convert the floats to doubles.

You need to force the entire expression to use floats by adding the f suffix to all of your literals.

Autres conseils

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).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top