Home > Java > javaTutorial > How to Avoid Floating-Point Precision Errors in Java?

How to Avoid Floating-Point Precision Errors in Java?

Susan Sarandon
Release: 2024-11-17 19:16:01
Original
221 people have browsed it

How to Avoid Floating-Point Precision Errors in Java?

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);
Copy after login

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
Copy after login

Addressing the Precision Errors

To avoid this issue, consider the following approaches:

  • Use Tolerance in Comparisons: When comparing floats or doubles for equality, allow for a small tolerance either way to account for the potential precision errors.
  • Use BigDecimal: Alternatively, utilize the BigDecimal class, which provides exact decimal representations of numbers. Here is an example:
BigDecimal step = new BigDecimal("0.1");
for (BigDecimal value = BigDecimal.ZERO;
     value.compareTo(BigDecimal.ONE) < 0;
     value = value.add(step)) {
    System.out.println(value);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template