Java程序中奇怪的浮点行为 [英] Strange floating-point behaviour in a Java program

查看:103
本文介绍了Java程序中奇怪的浮点行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我有一个包含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

为什么会发生这种情况?!

Why on earth could that happen?!

推荐答案

编程语言中浮点值最常见的存储 - 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.

原因是它们以二进制浮点格式存储值,而不是十进制浮点格式。可以精确表示的唯一小数值是两个负幂之和的小数值。数字如:

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这样的数字表示并不完全可以表示,因为它们不能表示为两个负幂的总和。因此,当以十进制小数打印出全精度时,它们将与原始值不匹配。

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆