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"); } } }
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:
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"); } } }
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:
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"); } } }
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"); } } }
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.
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?
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"); } } }
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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

Start Spring using IntelliJIDEAUltimate version...

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

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

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