为什么0.1 + 0.1 == 0.2? [英] Why 0.1 + 0.1 == 0.2?

查看:222
本文介绍了为什么0.1 + 0.1 == 0.2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与Java有关.据我了解,由于二进制表示,0.1不能完美地用Java表示.这使得

This is concerning Java. From what I've understood, 0.1 cannot be perfectly represented by Java because of binary representations. That makes

0.1 + 0.1 + 0.1 == 0.3

错误.但是,为什么

0.1 + 0.1 == 0.2

是真的吗?

推荐答案

由于二进制表示,

0.1不能用Java完美地表示.那使

0.1 cannot be perfectly represented by Java because of binary representations. That makes

0.1 + 0.1 + 0.1 == 0.3

0.1 + 0.1 + 0.1 == 0.3

否.

这不是相等性为假的全部原因,尽管它是其中的一部分. 0.3也不完全是3/10.碰巧0.2恰好是0.1的两倍(尽管它们分别不是2/10和1/10),并且加上0.1本身会产生一个值,该值也是您键入常数0.2.另一方面,在0.1 + 0.1 + 0.1运算之后获得的整体近似值与将0.3与3/10分开的近似值略有不同.

That is not the entire reason why the equality is false, although it is part of it. 0.3 is not exactly 3/10 either. It so happens that 0.2 is exactly twice 0.1 (although they are not respectively 2/10 and 1/10), and that adding 0.1 to itself produces the value that is also the one you get when you type the constant 0.2. On the other hand, the overall approximation that you get after the operations 0.1 + 0.1 + 0.1 is slightly different of the approximation separating 0.3 from 3/10.

如果我们使用带有5个有效数字的十进制,您可能会感到惊讶/1 * 3 * 3 == 1不成立(1/3将计算为0.33333,而3将计算为0.99999,这与1),而1/4 * 4 == 1确实成立(1/4的计算结果为0.25,而4的计算结果为1).

If we were using decimal with 5 significant digits, you might be surprised that 1 / 3 * 3 == 1 does not hold (1 / 3 would compute as 0.33333 and that times 3 would compute as 0.99999, which is different from 1), whereas 1 / 4 * 4 == 1 does hold (1 / 4 would compute as 0.25, and that times 4 would compute as 1).

您的问题与此类似,但适用于以2为基数的计算.每个常数和运算都是一个近似的机会.有时近似值不会发生,有时会发生但会抵消,因此最终结果比您有权期望的结果更准确.在0.1 + 0.1的情况下,结果不是2/10,但是它与写0.2时得到的2/10近似相同,因此等式成立.对于0.1 + 0.1 + 0.1,我们碰巧不是那么幸运.

Your question is somewhat similar to this, but for base-2 computations. Every constant and operation is an opportunity for an approximation. Sometimes the approximations do not happen, and sometimes they happen but cancel out, so that the end result is more accurate than you had a right to expect. In the case of 0.1 + 0.1, the result is not 2/10, but it is the same approximation of 2/10 that you get when you write 0.2, so that the equality holds. With 0.1 + 0.1 + 0.1 we happen not to be so lucky.

这篇关于为什么0.1 + 0.1 == 0.2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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