Java 程序中的奇怪浮点行为 [英] Strange floating-point behaviour in a Java program
问题描述
在我的程序中,我有一个包含 25 个双精度值 0.04 的数组当我尝试在循环中对这些值求和时,我得到以下结果:
In my program I have one array with 25 double values 0.04 When I try to sum these values in a loop I get following results:
0.0 + 0.04 = 0.04
0.04 + 0.04 = 0.08
0.08 + 0.04 = 0.12
0.12 + 0.04 = 0.16
0.16 + 0.04 = 0.2
0.2 + 0.04 = 0.24000000000000002
0.24000000000000002 + 0.04 = 0.28
0.28 + 0.04 = 0.32
0.32 + 0.04 = 0.36
0.36 + 0.04 = 0.39999999999999997
0.39999999999999997 + 0.04 = 0.43999999999999995
0.43999999999999995 + 0.04 = 0.4799999999999999
0.4799999999999999 + 0.04 = 0.5199999999999999
0.5199999999999999 + 0.04 = 0.5599999999999999
0.5599999999999999 + 0.04 = 0.6
0.6 + 0.04 = 0.64
0.64 + 0.04 = 0.68
0.68 + 0.04 = 0.7200000000000001
0.7200000000000001 + 0.04 = 0.7600000000000001
0.7600000000000001 + 0.04 = 0.8000000000000002
0.8000000000000002 + 0.04 = 0.8400000000000002
0.8400000000000002 + 0.04 = 0.8800000000000002
0.8800000000000002 + 0.04 = 0.9200000000000003
0.9200000000000003 + 0.04 = 0.9600000000000003
这到底是怎么回事?!
推荐答案
编程语言中最常见的浮点值存储 - IEEE 单打和双打 - 大多数小数没有精确表示.
The most common storage for floating-point values in programming languages - IEEE singles and doubles - does not have exact representations for most decimal fractions.
原因是它们以二进制浮点格式存储值,而不是十进制浮点格式.唯一可以精确表示的小数值是那些是 2 的负幂之和的小数值.像这样的数字:
The reason is that they store values in binary floating-point format, rather than decimal floating-point format. The only fractional values which can be represented exactly are those which are sums of negative powers of two. Numbers like:
- 0.5 (2^-1)
- 0.125 (2^-3)
- 0.625 (2^-1 + 2^-3)
等
您所看到的事实是,像 0.96 这样的数字表示不能完全表示,因为它们不能表示为 2 的负幂之和.因此,当以小数形式以全精度打印出来时,它们将与原始值不匹配.
What you are seeing is the fact that representations of numbers like 0.96 are not exactly representable, because they are not expressible as a sum of negative powers of two. Thus, when printed out with full precision as a decimal fraction, they won't match the original value.
这篇关于Java 程序中的奇怪浮点行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!