Avoiding Floating-Point Precision Errors with Floats and Doubles in Java
In Java, operations involving floating-point numbers (floats and doubles) can lead to precision errors. These errors arise because floats and doubles represent numbers in binary form, which does not provide exact representations for all decimal values.
Consider the following code:
for (float value = 0.0f; value < 1.0f; value += 0.1f) System.out.println(value);
Instead of the expected values, the output displays increments of 0.1 with a slight buildup of errors:
0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.70000005 0.8000001 0.9000001
Addressing the Precision Errors
To avoid this issue, consider the following approaches:
BigDecimal step = new BigDecimal("0.1"); for (BigDecimal value = BigDecimal.ZERO; value.compareTo(BigDecimal.ONE) < 0; value = value.add(step)) { System.out.println(value); }
This code will accurately represent and increment the value by 0.1, avoiding the accumulation of precision errors.
The above is the detailed content of How to Avoid Floating-Point Precision Errors in Java?. For more information, please follow other related articles on the PHP Chinese website!