为什么"0.2 + 0.1"显示为"0.30000000000000004"? [英] Why does '0.2 + 0.1' show as '0.30000000000000004'?
问题描述
我编写了以下代码来生成带浮点数的范围:
I have written the following code for generating a range with floats:
def drange(start, stop, step):
result = []
value = start
while value <= stop:
result.append(value)
value += step
return result
在使用以下语句调用此函数时:
When calling this function with this statement:
print drange(0.1,1.0,0.1)
我希望能得到这个:
[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
但是我得到了以下内容:
But I obtain the following, instead:
[0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999, 0.9999999999999999]
这是为什么?我该如何解决?
Why is this?, and how can I fix it?
推荐答案
这就是浮点数的工作方式.您无法在有限数量的位中表示无限数量的实数,因此存在一些截断.您应该看看 每个程序员应该了解的有关浮点算法的信息 :
That's how floating-point numbers work. You can't represent an infinite number of real numbers in a finite number of bits, so there is some truncation. You should take a look at What Every Programmer Should Know About Floating-Point Arithmetic:
为什么我的数字(例如0.1 + 0.2)加起来等于一轮好0.3,而我却得到了一个奇怪的结果,例如0.30000000000000004?
由于在内部,计算机使用的格式(二进制浮点数)根本无法精确表示0.1、0.2或0.3之类的数字.
Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.
在编译或解释代码时,"0.1"已经四舍五入为该格式的最接近的数字,即使在计算之前,也会产生小的四舍五入误差.
When the code is compiled or interpreted, your "0.1" is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.
使用 round(number,k)
将给定的浮点值四舍五入到小数点后的 k
位(因此,在您的情况下,请使用 round(数字,1)
代表一位数字.
Use round(number, k)
to round a given floating-point value to k
digits after the decimal (so in your case, use round(number, 1)
for one digit).
这篇关于为什么"0.2 + 0.1"显示为"0.30000000000000004"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!