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

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

问题描述

<块引用>

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

浮点数学有问题吗?

为什么在 Python Interpreter 中会出现以下情况?

<预><代码>>>>0.1+0.1+0.1-0.35.551115123125783e-17>>>0.1+0.10.2>>>0.2+0.10.30000000000000004>>>0.3-0.30.0>>>0.2+0.10.30000000000000004>>>

为什么不是0.2 + 0.1 = 0.3?

解决方案

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

<预><代码>>>>.1

Python 将以 .1 响应,因为它只打印到一定的精度,但已经有一个小的舍入误差..3 也会发生同样的情况,但是当你发出

<预><代码>>>>.2 + .10.30000000000000004

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

<预><代码>>>>.2 + .1 == .3错误的

Duplicates:
How is floating point stored? When does it matter?

Is floating point math broken?

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

Why doesn't 0.2 + 0.1 = 0.3?

解决方案

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

>>> .1

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

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天全站免登陆