Java precision loss

I have a problem with accuracy loss

My task is to print numbers as strings

int exponent = ... int[] Mantissas = { 1, 2, 5 }; double dataStep = java.lang.Math.pow(10.0, exponent) * Mantissas[mantissaIndex]; ... for (int i = 0; i < NSteps; i++) steps[i] = firstStep + i * dataStep; draw(steps); 

for example, 0.2 * 7 = 1.4000000000000001; 0.0000014 / 10 = 1.3999999999999998E-7

How to find out this problem?

UPD . The main problem is line-to- line formation. I'm not worried about losses of around 0.00000001. Now I solved it as String.format ("% f", value), but I think this is not a good approach

+1
source share
3 answers

As others have already mentioned, you should use java.math.BigDecimal instead of float / double. However, this is due to its own set of problems.

For example, when you call BigDecimal (double), the value you pass will expand to the full view:

 BigDecimal oneTenth = new BigDecimal(0.1); BigDecimal oneMillion = new BigDecimal(1000000); oneTenth.multiply(oneMillion) out> 100000.0000000000055511151231257827021181583404541015625000000 

But when you use the constructor of BigDecimal (String), the eact value is displayed, and you get

 BigDecimal oneTenth = new BigDecimal("0.1"); BigDecimalr oneMillion = new BigDecimal(1000000); oneTenth.multiply(oneMillion) out> 100000.0 

You can learn more about the BigDecimal limitations in Joshua Bloch and Neal Gafter for the excellent Java puzzlers and this informative article. Finally, note that toString in BigDecimal will print in scientific notation, so you will need to use toPlainString .

+3
source

The double type does not have infinite precision and cannot represent decimal numbers accurately. You observe normal rounding errors. For arbitrary precision arithmetic you will need to use java.math.BigDecimal.

+2
source

Search for "floating point numbers" on SO, and you'll get lots of answers about why this happens. This is due to the way floating point numbers are represented on computers.

How is a floating point stored? When does it matter?

Another article on this subject is Floating Point Approximation

+1
source

All Articles