Python odd operation?

自作多情 提交于 2019-12-23 03:19:09

问题


Can somebody please explain me why the code below behaves like it does? (It's Python in command line on Windows7 x64)

>>>2.22 + 0.22
2.44000000000000004
>>>(222+22)/100
2.44

回答1:


Floating point operations are limited in percision, and in python the limitations are well documented. You can read about it here




回答2:


All floating point math is like this and is based on the IEEE standard.




回答3:


Floating point oprations are known to cause errors.

http://en.wikipedia.org/wiki/IEEE_floating_point

Use the decimal module if you want precise calculations.




回答4:


this is due to the data format.

2.22 + 0.22 != 2.44  // both are float
// when you use them to calculate, they are giving consistently "wrong" results
// because the datatype in itself gets incorrect when moving into deep comma space
(222+22) / 100 // becomes this in calculation
222+22 = 244 --> 244/100 = 2.44 



回答5:


The numbers you are adding are in float format. That means it has decimal places. The second line of maths' numbers are all integers, so they are in integer form. Float form is known to throw errors whilst carrying out maths equations.



来源:https://stackoverflow.com/questions/13266732/python-odd-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!