浮点数的Python表示形式 [英] Python representation of floating point numbers

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

问题描述

我今天花了一个小时试图找出原因

I spent an hour today trying to figure out why

return abs(val-desired) <= 0.1

尽管valdesired的绝对差为<=0.1,但

偶尔会返回False.经过一些调试后,我发现了-13.2 + 13.3 = 0.10000000000000142.现在我了解到CPU无法轻松表示大多数实数,但这是一个例外,因为您可以减去0.00000000000000142并得到0.1,因此可以用Python表示.

was occasionally returning False, despite val and desired having an absolute difference of <=0.1. After some debugging, I found out that -13.2 + 13.3 = 0.10000000000000142. Now I understand that CPUs cannot easily represent most real numbers, but this is an exception, because you can subtract 0.00000000000000142 and get 0.1, so it can be represented in Python.

我正在Intel Core架构CPU上运行Python 2.7(这是我能够对其进行测试的全部).我很好奇我如何存储0.1值,尽管无法将算术应用于特定的浮点值. valdesiredfloat值.

I am running Python 2.7 on Intel Core architecture CPUs (this is all I have been able to test it on). I'm curious to know how I can store a value of 0.1 despite not being able to apply arithmetic to particular floating point values. val and desired are float values.

推荐答案

是的,这可能有点令人惊讶:

Yes, this can be a bit surprising:

>>> +13.3
13.300000000000001
>>> -13.2
-13.199999999999999
>>> 0.1
0.10000000000000001

所有这些数字可以用大约16位数字表示.那为什么:

All these numbers can be represented with some 16 digits of accuracy. So why:

>>> 13.3-13.2
0.10000000000000142

在这种情况下,为什么精度只有14位?

Why only 14 digits of accuracy in that case?

好吧,这是因为13.3和-13.2的精度为16位数字,这意味着14个小数点,因为小数点前有两位数字.因此,结果还具有14个小数点的准确性.即使计算机可以表示16位数字.

Well, that's because 13.3 and -13.2 have 16 digits of accuracy, which means 14 decimal points, since there are two digits before the decimal point. So the result also have 14 decimal points of accuracy. Even though the computer can represent numbers with 16 digits.

如果我们增大数字,则结果的准确性会进一步降低:

If we make the numbers bigger, the accuracy of the result decreases further:

>>> 13000.3-13000.2
0.099999999998544808

>>> 1.33E10-13.2E10
-118700000000.0

简而言之,结果的准确性取决于输入的准确性.

In short, the accuracy of the result depends on the accuracy of the input.

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

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