有人可以解释一下:0.2 + 0.1 = 0.30000000000000004吗? [英] Can someone explain this: 0.2 + 0.1 = 0.30000000000000004?

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

问题描述

可能重复:
如何存储浮点数?什么时候重要?

Possible Duplicate:
How is floating point stored? When does it matter?

为什么在Python解释器中会发生以下情况?

Why does the following occur in the Python Interpreter?

>>> 0.1+0.1+0.1-0.3
5.551115123125783e-17
>>> 0.1+0.1
0.2
>>> 0.2+0.1
0.30000000000000004
>>> 0.3-0.3
0.0
>>> 0.2+0.1
0.30000000000000004
>>> 

为什么不0.2 + 0.1 = 0.3?

推荐答案

这是因为.1不能以二进制浮点表示形式精确表示.如果您尝试

That's because .1 cannot be represented exactly in a binary floating point representation. If you try

>>> .1

Python将使用.1进行响应,因为它只能打印到一定的精度,但是已经存在一个很小的舍入错误. .3也会发生同样的情况,但是当您发出

Python will respond with .1 because it only prints up to a certain precision, but there's already a small round-off error. The same happens with .3, but when you issue

>>> .2 + .1
0.30000000000000004

然后,会累积.2.1中的舍入误差.另请注意:

then the round-off errors in .2 and .1 accumulate. Also note:

>>> .2 + .1 == .3
False

这篇关于有人可以解释一下:0.2 + 0.1 = 0.30000000000000004吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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