浮点数的Python舍入错误 [英] Python rounding error with float numbers
问题描述
我不知道这是否是一个明显的错误,但是在运行 Python 脚本以改变模拟参数时,我意识到 delta = 0.29 和 delta = 0.58 的结果丢失了.在调查中,我注意到以下 Python 代码:
I don't know if this is an obvious bug, but while running a Python script for varying the parameters of a simulation, I realized the results with delta = 0.29 and delta = 0.58 were missing. On investigation, I noticed that the following Python code:
for i_delta in range(0, 101, 1):
delta = float(i_delta) / 100
(...)
filename = 'foo' + str(int(delta * 100)) + '.dat'
为 delta = 0.28 和 0.29 生成相同的文件,与 .57 和 .58 相同,原因是 python 将 float(29)/100 返回为 0.28999999999999998.但这不是系统性错误,并不是每个整数都会发生这种错误.所以我创建了以下 Python 脚本:
generated identical files for delta = 0.28 and 0.29, same with .57 and .58, the reason being that python returns float(29)/100 as 0.28999999999999998. But that isn't a systematic error, not in the sense it happens to every integer. So I created the following Python script:
import sys
n = int(sys.argv[1])
for i in range(0, n + 1):
a = int(100 * (float(i) / 100))
if i != a: print i, a
而且我看不到发生这种舍入错误的数字中的任何模式.为什么这些特定数字会发生这种情况?
And I can't see any pattern in the numbers for which this rounding error happens. Why does this happen with those particular numbers?
推荐答案
任何不能由 2 的精确幂构建的数字都不能精确地表示为浮点数;它需要被近似.有时最接近的近似值会小于实际数字.
Any number that can't be built from exact powers of two can't be represented exactly as a floating point number; it needs to be approximated. Sometimes the closest approximation will be less than the actual number.
这篇关于浮点数的Python舍入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!