为什么Python的节目`0.2 + 0.1`为'0.30000000000000004`? [英] Why does Python show `0.2 + 0.1` as `0.30000000000000004`?

查看:1161
本文介绍了为什么Python的节目`0.2 + 0.1`为'0.30000000000000004`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的code用于生成与花车范围:

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

当调用本声明此功能:

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?

谢谢!

推荐答案

这是如何浮点数的工作。不能重新present实数的无限数目在一个有限数目的位,所以有一些截短。你应该看一看 什么每个程序员应该知道关于浮点运算

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?

由于内部,电脑使用的格式(二进制浮点)不能准确地重新present一个像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.

当code编译或间preTED,你的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.

使用圆(周数,k)小数点后四舍五入给定的浮点值 K 数字(所以你的情况下,使用轮(数字,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).

这篇关于为什么Python的节目`0.2 + 0.1`为'0.30000000000000004`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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