Home >Java >javaTutorial >Why double Loses Precision and How to Avoid It in Java

Why double Loses Precision and How to Avoid It in Java

Patricia Arquette
Patricia ArquetteOriginal
2025-01-27 18:09:10965browse

Why double Loses Precision and How to Avoid It in Java

When working with floating point numbers in Java, you may notice that double sometimes produces unexpected or imprecise results. This behavior can lead to errors, especially in financial applications or scenarios that require high accuracy.

In this article, we will delve into the root cause of this problem, explain how to avoid it, provide a working example, and explore whether newer Java versions provide better alternatives.

Why does double lose precision?

1. IEEE 754 floating point standard

The double data type in Java follows the IEEE 754 floating point number operation standard. It represents numbers in binary format using:

  • 1 bit is used for symbols,
  • 11 bits for exponent,
  • 52 bits are used for fractions (mantissa).

This binary representation introduces limitations:

  • Limited precision: double can only accurately represent up to 15-17 decimal digits.
  • Rounding Error: Many decimal fractions (e.g., 0.1) cannot be represented exactly as binary numbers, resulting in rounding errors.

For example, in binary:

  • 0.1 becomes an infinitely recurring decimal that is truncated for storage, thereby introducing slight inaccuracies.

2. Cumulative error in arithmetic operations

Operations involving double may accumulate errors:

  • Repeated additions/subtractions amplify rounding errors.
  • Multiplication/division may lose precision due to truncation.

This behavior is inherent to floating point arithmetic and is not unique to Java.


Workable example: precision loss caused by using double

Here is an example demonstrating the problem:

<code class="language-java">public class DoublePrecisionLoss {
    public static void main(String[] args) {
        double num1 = 0.1;
        double num2 = 0.2;
        double sum = num1 + num2;

        System.out.println("预期和:0.3");
        System.out.println("实际和:" + sum);

        // 比较
        if (sum == 0.3) {
            System.out.println("和等于0.3");
        } else {
            System.out.println("和不等于0.3");
        }
    }
}</code>

Output:

<code>预期和:0.3
实际和:0.30000000000000004
和不等于0.3</code>

The result 0.30000000000000004 highlights the rounding error caused by the binary representation. Even trivial differences can cause major problems in critical systems.


How to avoid accuracy loss

1. Use BigDecimal for precise calculations

The BigDecimal class in Java provides arbitrary precision arithmetic, making it ideal for scenarios that require high precision (such as financial calculations).

Example using BigDecimal:

<code class="language-java">import java.math.BigDecimal;

public class BigDecimalExample {
    public static void main(String[] args) {
        BigDecimal num1 = new BigDecimal("0.1");
        BigDecimal num2 = new BigDecimal("0.2");
        BigDecimal sum = num1.add(num2);

        System.out.println("预期和:0.3");
        System.out.println("实际和:" + sum);

        // 比较
        if (sum.compareTo(new BigDecimal("0.3")) == 0) {
            System.out.println("和等于0.3");
        } else {
            System.out.println("和不等于0.3");
        }
    }
}</code>

Output:

<code>预期和:0.3
实际和:0.3
和等于0.3</code>

By using BigDecimal, precision issues are eliminated and comparisons produce correct results.

2. Use Epsilon value for comparison

Another way to deal with loss of precision is to compare floating point numbers with a tolerance (epsilon). This method checks whether the numbers are "close enough" rather than relying on exact equality.

Example using Epsilon comparison:

<code class="language-java">public class EpsilonComparison {
    public static void main(String[] args) {
        double num1 = 0.1;
        double num2 = 0.2;
        double sum = num1 + num2;
        double epsilon = 1e-9; // 定义一个小的容差值

        System.out.println("预期和:0.3");
        System.out.println("实际和:" + sum);

        // 使用epsilon进行比较
        if (Math.abs(sum - 0.3) < epsilon) {
            System.out.println("和大约等于0.3");
        } else {
            System.out.println("和不等于0.3");
        }
    }
}</code>

Output:

<code class="language-java">public class DoublePrecisionLoss {
    public static void main(String[] args) {
        double num1 = 0.1;
        double num2 = 0.2;
        double sum = num1 + num2;

        System.out.println("预期和:0.3");
        System.out.println("实际和:" + sum);

        // 比较
        if (sum == 0.3) {
            System.out.println("和等于0.3");
        } else {
            System.out.println("和不等于0.3");
        }
    }
}</code>

Why use Epsilon to compare?

  • Flexibility : It allows small differences caused by the incorporation error.
  • Simple
  • : This method does not require external libraries and efficiency is high.
Use Apache Commons Math to enhance accuracy

Apache Commons Math is a library designed for complex mathematical computing. Although it does not provide arbitrary accuracy arithmetic like Bigdecimal, it provides practical procedures that simplify numerical operations and minimize floating -point errors in some cases.

Example: Use precision.equals to compare

Output:
<code>预期和:0.3
实际和:0.30000000000000004
和不等于0.3</code>

Why use Apache Commons math?

<code class="language-java">import java.math.BigDecimal;

public class BigDecimalExample {
    public static void main(String[] args) {
        BigDecimal num1 = new BigDecimal("0.1");
        BigDecimal num2 = new BigDecimal("0.2");
        BigDecimal sum = num1.add(num2);

        System.out.println("预期和:0.3");
        System.out.println("实际和:" + sum);

        // 比较
        if (sum.compareTo(new BigDecimal("0.3")) == 0) {
            System.out.println("和等于0.3");
        } else {
            System.out.println("和不等于0.3");
        }
    }
}</code>

Simplified comparison

: Precision.equals allows the use of specified tolerant to compare with the specified tolerance, so as to easily handle the incorporation error.
  • Lightweight : The library provides tools that focus on numerical calculations without increasing the expenses of BigDecimal.
  • Summary
  • Understanding the limitation
: Double itself is not defective, but because its binary floating point representation, it is not suitable for high -precision tasks.

Bigdecimal

: Bigdecimal can ensure accuracy, but may affect performance for financial or critical calculations.
  • Using library : Apache Commons Math provides practical programs such as Precision.equals, which can effectively handle floating -point comparison.
  • By understanding Double and its alternatives, you can write more robust and more accurate Java applications.
  • If you encounter the accuracy of Double and how to solve these problems, please tell me in the comments! ?

The above is the detailed content of Why double Loses Precision and How to Avoid It in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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