Python浮点舍入错误 [英] Python Float rounding errors

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

问题描述

使用列表理解表达式时:

When using list comprehension expression:

[x * 0.1 for x in range(0, 5)]

我希望得到这样的列表:

I expect to get a list like this:

[0.0, 0.1, 0.2, 0.3, 0.4]

但是我得到了这个:

[0.0, 0.1, 0.2, 0.30000000000000004, 0.4]

这背后的原因是什么?

推荐答案

浮动在几乎所有语言中本质上都是不精确的

floats are inherently imprecise in pretty much every language

如果您需要精确的精度,请使用 Decimal

if you need exact precision use the Decimal class

from decimal import Decimal
print Decimal("0.3")

如果你只是想让它们看起来漂亮,那么在显示时使用格式字符串例如:

if you just need them to look pretty just use format strings when displaying eg :

"%0.2f"%2.030000000000034

如果你想比较它们,请使用一些阈值

if you want to compare them use some threshold

if num1 - num2 < 1e-3 : print "Equal Enough For Me!"

**请参阅 abarnert 对阈值的评论......这是一个非常简化的示例,用于更深入地解释 epsilon 阈值,我在这里找到了一篇文章 http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm

**see abarnert's comments on thresholding ... this is a very simplified example for a more indepth explanation of epsilon thresholding one article I found is here http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm

补充阅读:

http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html(详细说明)

http://floating-point-gui.de/basic/(基础教程一般用于使用浮点数)

http://floating-point-gui.de/basic/ (basic tutorial for working with floats in general)

这篇关于Python浮点舍入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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