Python Shell - “Extras”在浮动减法 [英] Python Shell - "Extras" in float subtraction

查看:220
本文介绍了Python Shell - “Extras”在浮动减法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

浮点限制


在这里使用Python 2.7。



有人可以解释为什么在shell中发生这种情况吗?

 > ;>> 5.2-5.0 
0.20000000000000018

搜索的结果不同, (数量很少,数量也很大),但看起来相当普遍,考虑到我使用的数字是相同的,我不认为这就是为什么会发生这种情况。编辑:我想我没有定义这件事发生我的意思是,它返回0.2 ... 018,而不是简单地导致0.2。我得到了这个打印轮,并删除了代码段中的打印部分,因为这是误导。

解决方案

您需要了解那5.2-5.0真的是0.20000000000000018,不是0.2。有关这方面的标准说明,请参阅计算机科学家应了解的浮点运算

如果你不想阅读所有这些,只要接受5.2,5.0和0.20000000000000018都是近似的,就像计算机一样可以得到你真正的数字。

Python有一些技巧,让你不知道每个计算机科学家应该知道什么,仍然摆脱它。主要的技巧是将 str(f) - 也就是说,浮点数字的可读格式 - 被截断为12个有效数字,所以 str(5.2-5.0)0.2,而不是0.20000000000000018 。但是有时你需要所有的精度,所以 repr(f) - 也就是机器可读格式不会被截断,所以 repr(5.2-5.0)0.20000000000000018



现在唯一留下来了解的是解释器外壳。正如Ashwini Chaudhary所解释的那样,只是在shell中进行评估时,会打印出 repr ,而 print code> str 。


Possible Duplicate:
Floating Point Limitations

Using Python 2.7 here.

Can someone explain why this happens in the shell?

>>> 5.2-5.0
0.20000000000000018

Searching yielded things about different scales of numbers not producing the right results (a very small number and a very large number), but that seemed pretty general, and considering the numbers I'm using are of the same scale, I don't think that's why this happens.

EDIT: I suppose I didn't define that the "this thing happening" I meant was that it returns 0.2 ... 018 instead of simply resulting in 0.2. I get that print rounds, and removed the print part in the code snippet, as that was misleading.

解决方案

You need to understand that 5.2-5.0 really is 0.20000000000000018, not 0.2. The standard explanation for this is found in What Every Computer Scientist Should Know About Floating-Point Arithmetic.

If you don't want to read all of that, just accept that 5.2, 5.0, and 0.20000000000000018 are all just approximations, as close as the computer can get to the numbers you really way.

Python has some tricks to allow you to not know what every computer scientist should know and still get away with it. The main trick is that str(f)—that is, the human-readable rendition of a floating-point number—is truncated to 12 significant digits, so str(5.2-5.0) is "0.2", not "0.20000000000000018". But sometimes you need all the precision you can get, so repr(f)—that is, the machine-readable rendition—is not truncated, so repr(5.2-5.0) is "0.20000000000000018".

Now the only thing left to understand is what the interpreter shell does. As Ashwini Chaudhary explains, just evaluating something in the shell prints out its repr, while the print statement prints out its str.

这篇关于Python Shell - “Extras”在浮动减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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