为什么`0.4 / 2`等于`0.2`,同时`0.6 / 3`等于`python中的0.19999999999999998`? [英] Why `0.4/2` equals to `0.2` meanwhile `0.6/3` equals to `0.19999999999999998` in python?

查看:528
本文介绍了为什么`0.4 / 2`等于`0.2`,同时`0.6 / 3`等于`python中的0.19999999999999998`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这些是浮点除法。但为什么这两个公式的表现不一样呢?我还做了一些调查,结果让我更加困惑:

 >>> 0.9 / 3 
0.3

>>> 1.2 / 3
0.39999999999999997

>>> 1.5 / 3
0.5

这里的逻辑决定是否打印结果是否有一位小数或更多?



PS:我用python3.4来做上面的实验。 b $ b

解决方案

因为浮点结果的确切值略有不同。

 >>> '%.56f'%0.4 
'0.40000000000000002220446049250313080847263336181640625000'
>>> '%.56f'%(0.4 / 2)
'0.20000000000000001110223024625156540423631668090820312500'
>>> '%.56f'%0.6
'0.59999999999999997779553950749686919152736663818359375000'
>>> '%.56f'%(0.6 / 3)
'0.19999999999999998334665463062265189364552497863769531250'
>>> '%.56f'%0.2
'0.20000000000000001110223024625156540423631668090820312500'
>>> (0.2 - 0.6 / 3)== 2.0 ** - 55
True

可以看到,打印为0.2的结果确实稍微接近0.2。我在最后加上了这个位,告诉你这两个数字之间的区别是什么。 (如果你很好奇,上面的表示就是确切的值 - 除此之外,增加任何数字只是增加了更多的零)。

I know these are float point division. But why did these two formula behave differently?

And I did some more investigation, the result confusing me even more:

>>>0.9/3
0.3

>>>1.2/3
0.39999999999999997

>>>1.5/3
0.5

What's the logic here to decide whether the result is printed with one decimal place or more?

PS: I used python3.4 to do the experiment above.

解决方案

Because the exact values of the floating point results are slightly different.

>>> '%.56f' % 0.4
'0.40000000000000002220446049250313080847263336181640625000'
>>> '%.56f' % (0.4/2)
'0.20000000000000001110223024625156540423631668090820312500'
>>> '%.56f' % 0.6
'0.59999999999999997779553950749686919152736663818359375000'
>>> '%.56f' % (0.6/3)
'0.19999999999999998334665463062265189364552497863769531250'
>>> '%.56f' % 0.2
'0.20000000000000001110223024625156540423631668090820312500'
>>> (0.2 - 0.6/3) == 2.0**-55
True

As you can see, the result that is printed as "0.2" is indeed slightly closer to 0.2. I added the bit at the end to show you what the exact value of the difference between these two numbers is. (In case you're curious, the above representations are the exact values - adding any number of digits beyond this just adds more zeroes).

这篇关于为什么`0.4 / 2`等于`0.2`,同时`0.6 / 3`等于`python中的0.19999999999999998`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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