Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Machine Epsilon

Tags:

java

precision

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.

like image 828
But I'm Not A Wrapper Class Avatar asked Feb 06 '14 16:02

But I'm Not A Wrapper Class


People also ask

What is machine epsilon used for?

Represents the round-off error for a floating-point number with a given precision. Use the machine epsilon constant to compare whether two floating-point numbers are equivalent.

What is the value of machine epsilon?

The machine epsilon (in double precision) is eps =2.220446049250313e−016. It is obtained when the number of terms is n =53.

What is machine epsilon C++?

Machine Epsilon is a machine-dependent floating point value that provides an upper bound on relative error due to rounding in floating point arithmetic. Mathematically, for each floating point type, it is equivalent to the difference between 1.0 and the smallest representable value that is greater than 1.0.

What is machine epsilon in Matlab?

The epsilon of the machine (short: eps) is the minimum distance that a floating point arithmetic program like Matlab can recognize between two numbers x and y.


2 Answers

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.

like image 155
SLaks Avatar answered Oct 13 '22 15:10

SLaks


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.

like image 27
Ingo Avatar answered Oct 13 '22 15:10

Ingo