posted 5 years ago

Did any one ran into this issue with IEEEremainder?

tc1 = java.lang.Math.IEEEremainder(8050 , 50);

System.out.println (" number: 8050 result: "+tc1);

>>> outputs ... number: 8050 result: 0.0

tc1 = java.lang.Math.IEEEremainder( (8.05*1000) , 50);

System.out.println (" number: 8.05 * 1000 result: "+tc1);

>>> outputs ... number: 8.05 * 1000 result: 9.094947017729282E-13

Is this a bug in Java software?

Did any one ran into this issue with IEEEremainder?

tc1 = java.lang.Math.IEEEremainder(8050 , 50);

System.out.println (" number: 8050 result: "+tc1);

>>> outputs ... number: 8050 result: 0.0

tc1 = java.lang.Math.IEEEremainder( (8.05*1000) , 50);

System.out.println (" number: 8.05 * 1000 result: "+tc1);

>>> outputs ... number: 8.05 * 1000 result: 9.094947017729282E-13

Is this a bug in Java software?

posted 5 years ago

- 1

No, it's not a Java bug. It's the result of the fact that many fractions that can be represented exactly in base-10 cannot be represented exactly in base-2, and even those that can may require more bits than exist in any finite-width representation.

For instance, it it not possible to represent 1/10th (0.1 in base-10) in base-2 in a finite number of digits. So IEEE 754, used by float and double in Java, C, and many others, cannot store the value 0.1. Similarly, since 0.05 cannot be represented by a finite sequence of negative powers of 2, it cannot be stored exactly in a double.

There are more details at: http://cr.yp.to/2005-590/goldberg.pdf. That's a fairly heavy technical read. you should be able to google for simpler explanations if needed.

You can either use one of the following to format the output:

java.text.DecimalFormat

java.lang.String#format(java.lang.String, java.lang.Object...)

java.io.PrintStream#printf(java.lang.String, java.lang.Object...)

Or, if you actually need to

For instance, it it not possible to represent 1/10th (0.1 in base-10) in base-2 in a finite number of digits. So IEEE 754, used by float and double in Java, C, and many others, cannot store the value 0.1. Similarly, since 0.05 cannot be represented by a finite sequence of negative powers of 2, it cannot be stored exactly in a double.

There are more details at: http://cr.yp.to/2005-590/goldberg.pdf. That's a fairly heavy technical read. you should be able to google for simpler explanations if needed.

You can either use one of the following to format the output:

java.text.DecimalFormat

java.lang.String#format(java.lang.String, java.lang.Object...)

java.io.PrintStream#printf(java.lang.String, java.lang.Object...)

Or, if you actually need to

**store**the value exactly, instead of just storing with precision of about 1 part in 10^18, such as for monetary calculations, you can use BigDecimal.