python浮点数表达,浮点数的Python表示形式

I spent an hour today trying to figure out why

return abs(val-desired) <= 0.1

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.

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

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

>>> 13.3-13.2

0.10000000000000142

Why only 14 digits of accuracy in that case?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值