Table of Contents
Why does double lose precision?
1. IEEE 754 floating point standard
2. Cumulative error in arithmetic operations
Workable example: precision loss caused by using double
How to avoid accuracy loss
1. Use BigDecimal for precise calculations
Example using BigDecimal:
2. Use Epsilon value for comparison
Example using Epsilon comparison:
Why use Epsilon to compare?
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.
Simplified comparison
Bigdecimal
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

Jan 27, 2025 pm 06:09 PM

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:

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

Output:

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

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:

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

Output:

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

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:

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

Output:

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

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

Why use Apache Commons math?

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles