Why is there a risk of precision loss during floating-point operations? How to solve the problem of loss of precision in floating-point arithmetic?

Why is there a risk of precision loss during floating-point operations?

Code demo for loss of precision in floating-point arithmetic:

float a = 2.0f - 1.9f;
float b = 1.8f - 1.7f;
System.out.println(a);// 0.100000024
System.out.println(b);// 0.099999905
System.out.println(a == b);// false

Why does this problem arise?

This has a lot to do with the mechanism by which computers store floating-point numbers. We know that the computer is binary, and when the computer represents a number, the width is limited, and the infinite loop of decimals can only be truncated when stored in the computer, so the precision of the decimal will be lost. This also explains why floating-point numbers cannot be accurately represented in binary.

For example, 0.2 in decimal cannot be accurately converted into a binary decimal:

// 0.2 转换为二进制数的过程为,不断乘以 2,直到不存在小数为止,
// 在这个计算过程中,得到的整数部分从上到下排列就是二进制的结果。
0.2 * 2 = 0.4 -> 0
0.4 * 2 = 0.8 -> 0
0.8 * 2 = 1.6 -> 1
0.6 * 2 = 1.2 -> 1
0.2 * 2 = 0.4 -> 0(发生循环)
...

For more information about floating-point numbers, I suggest you read the article Computer System Basics (4) Floating-point Numbers .

How to solve the problem of loss of precision in floating-point arithmetic?

BigDecimalOperations on floating-point numbers can be realized without loss of precision. Usually, most business scenarios (such as scenarios involving money) that require precise calculation results of floating point numbers are BigDecimaldone through .

BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("0.9");
BigDecimal c = new BigDecimal("0.8");

BigDecimal x = a.subtract(b);
BigDecimal y = b.subtract(c);

System.out.println(x); /* 0.1 */
System.out.println(y); /* 0.1 */
System.out.println(Objects.equals(x, y)); /* true */

For BigDecimala detailed introduction to , you can read this article I wrote: BigDecimal Detailed Explanation .

Guess you like

Origin blog.csdn.net/qq_34337272/article/details/130035600