为什么“0.2 + 0.1"显示为“0.30000000000000004"? [英] Why does '0.2 + 0.1' show as '0.30000000000000004'?

查看:24
本文介绍了为什么“0.2 + 0.1"显示为“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]

但我得到以下信息:

[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屋!

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