基本减法中的Python错误? [英] Python error in basic subtraction?

查看:45
本文介绍了基本减法中的Python错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
浮点数的 Python 舍入错误
python 数学是错误的

我无法让 Python 正确执行减法 1 - 0.8 并分配它.它不断提出错误的答案,0.19999999999999996.

I can't get Python to correctly do the subtraction 1 - 0.8 and assign it. It keeps coming up with the incorrect answer, 0.19999999999999996.

我探索了一下:

sq = {}
sub = {}
for i in range(1000):
    sq[str(i/1000.)+'**2']=((i/1000.)**2)
    sub['1-'+str(i/1000.)]=(1.0-(i/1000.))

并发现此错误发生在 0 到 1 到小数点后第三位之间的一组有点随机的浮点数上.当您将这些浮点数平方时,也会发生类似的错误,但要对不同的子集进行平方.

and discovered that this error happens with a somewhat random group of the floats between 0 and 1 to the third decimal place. A similar error also occurs when you square those floats, but to a different subset.

我希望得到对此的解释以及如何让 Python 正确执行算术运算.使用 round(x,3) 是我目前使用的解决方法,但它并不优雅.

I'm hoping for an explanation of this and how to make Python do the arithmetic right. Using round(x,3) is the work-around I'm using for now, but it's not elegant.

谢谢!

这是我的 Python 2.7.3 shell 中的一个会话:

This is a session in my Python 2.7.3 shell:

*** Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32. ***
*** Remote Python engine  is active ***
>>> 1-0.8
0.19999999999999996
>>> print 1-0.8
0.2
>>> a = 1-0.8
>>> a
0.19999999999999996
>>> print a
0.2
>>> a = 0.2
>>> print a
0.2
>>> a
0.2
>>> 

这是我放入几个在线解释器的代码:

Here's the code I put into a couple online interpreters:

def doit():
    d = {'a':1-0.8}
    return d

print doit()

和输出:

{'a': 0.19999999999999996}

推荐答案

浮点数不能像您期望的那样工作.

Floating numbers don't work as you're expecting them to.

对于初学者,请阅读浮点指南.长话短说:计算机将浮点数表示为二进制,结果证明将精确的十进制小数存储为二进制是不可能的 (自己尝试,看看为什么).出于实际目的,0.19999999999999996 与 0.2足够接近".如果您想将其打印为 0.2,那么您可以执行以下操作:

For starters, read the floating point guide. Long story short: computers represent floating point numbers as binary, and it turns out that storing a precise decimal fraction as binary is not possible (try it for yourself on paper to see why). For practical purposes, 0.19999999999999996 is "close enough" to 0.2. If you wanted to print it as 0.2, then you could do something like:

print "%0.1f" % floating_point_value

所以你看到的不是错误.这是预期的行为.

So what you're seeing isn't an error. It's expected behavior.

这篇关于基本减法中的Python错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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