Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will floating point operations on the JVM give the same results on all platforms?

I'm using Java in an application running on multiple machines, and all machines need to get the same results for mathematical operations. Is it safe to use Java's floating point primitives? Or should I just use a fixed-point math library?

like image 733
Eamonn M.R. Avatar asked Mar 11 '14 19:03

Eamonn M.R.


People also ask

Does Java use floating point?

Java uses a subset of the IEEE 754 binary floating point standard to represent floating point numbers and define the results of arithmetic operations. Virtually all modern computers conform to this standard. A float is represented using 32 bits, and each possible combination of bits represents one real number.

What does floating point mean in Java?

Floating-point numbers are used to represent numbers that have a decimal point in them (such as 5.3 or 99.234). Whole numbers can also be represented, but as a floating point, the number 5 is actually 5.0. In Java, floating-point numbers are represented by the types float and double.

What are floating point operations used for?

In computing, floating point operations per second (FLOPS, flops or flop/s) is a measure of computer performance, useful in fields of scientific computations that require floating-point calculations. For such cases, it is a more accurate measure than measuring instructions per second.

How accurate is floating point?

This means that floating point numbers have between 6 and 7 digits of precision, regardless of exponent. That means that from 0 to 1, you have quite a few decimal places to work with. If you go into the hundreds or thousands, you've lost a few.


2 Answers

Not in general, no. However, you can use strictfp expressions:

Within an FP-strict expression, all intermediate values must be elements of the float value set or the double value set, implying that the results of all FP-strict expressions must be those predicted by IEEE 754 arithmetic on operands represented using single and double formats.

Within an expression that is not FP-strict, some leeway is granted for an implementation to use an extended exponent range to represent intermediate results; the net effect, roughly speaking, is that a calculation might produce "the correct answer" in situations where exclusive use of the float value set or double value set might result in overflow or underflow.

like image 149
Jon Skeet Avatar answered Nov 04 '22 16:11

Jon Skeet


In addition to strictfp, there's also StrictMath which requires that the results be predictable for transcendental and other functions.

like image 29
ajb Avatar answered Nov 04 '22 14:11

ajb