0.1 + 0.2 != 0.3?

Floating Point Math
Your language isn’t broken, it’s doing floating point math. Computers can only natively store integers, so they need some way of representing decimal numbers. This representation is not perfectly accurate. This is why, more often than not, 0.1 + 0.2 != 0.3.

Why does this happen?
It’s actually rather interesting. When you have a base-10 system (like ours), it can only express fractions that use a prime factor of the base. The prime factors of 10 are 2 and 5. So 1/2, 1/4, 1/5, 1/8, and 1/10 can all be expressed cleanly because the denominators all use prime factors of 10. In contrast, 1/3, 1/6, 1/7 and 1/9 are all repeating decimals because their denominators use a prime factor of 3 or 7.

In binary (or base-2), the only prime factor is 2, so you can only cleanly express fractions whose denominator has only 2 as a prime factor. In binary, 1/2, 1/4, 1/8 would all be expressed cleanly as decimals, while 1/5 or 1/10 would be repeating decimals. So 0.1 and 0.2 (1/10 and 1/5), while clean decimals in a base-10 system, are repeating decimals in the base-2 system the computer uses. When you perform math on these repeating decimals, you end up with leftovers which carry over when you convert the computer’s base-2 (binary) number into a more human-readable base-10 representation.

Below are some examples of sending .1 + .2 to standard output in a variety of languages.

翻译如下:
浮点数学
您的语言没有坏,正在做浮点运算。计算机只能本地存储整数,因此它们需要某种表示十进制数字的方式。此表示并不完全准确。这就是为什么(通常不是)的原因 0.1 + 0.2 != 0.3。

为什么会这样?
实际上,这很有趣。当您有一个以10为底的系统(如我们的系统)时,它只能表示使用该底数的质数的分数。10的素数是2和5。因此,由于分母都使用10的素数,所以1 / 2、1 / 4、1 / 5、1 / 8和1/10都可以清楚地表示。 / 3、1 / 6、1 / 7和1/9都是重复的小数,因为它们的分母使用3或7的质数。

在二进制(或以2为基数)中,唯一的质数是2,因此您只能清楚地表达分母只有2作为质数的分数。以二进制形式,1 / 2、1 / 4、1 / 8都将干净地表示为小数,而1/5或1/10将重复小数。因此,在以10为基数的系统中使用干净的小数时,0.1和0.2(1/10和1/5)在计算机使用的以2为基数的系统中重复小数。当您对这些重复的小数进行数学运算时,最终会剩下余数,当您将计算机的以2为底的(二进制)数字转换为更易于理解的以10为底的表示形式时,这些余数就会保留下来。

以下是使用.1 + .2多种语言发送到标准输出的一些示例。

在Java中的情况:Java使用BigDecimal类内置了对任意精度数字的支持。
在这里插入图片描述
所有语言中的情况:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
参考:《2020最新Java基础精讲视频教程和学习路线!》
原文链接:https://segmentfault.com/a/1190000039036761

猜你喜欢

转载自blog.csdn.net/weixin_46699878/article/details/112936000