浮动随机(?!)精确怪癖

raa*_*m86 5 python

我刚开始学习python,我偶然发现了一个特殊性

python版本:

Python 2.7.2(默认,2011年7月20日,02:32:18)[gCC 4.2.1(LLVM,Emscripten 1.5,Empythoned)]在linux2上

on:http://repl.it/languages/Python

使用解释器分配:

    pi = 3.141 // 3 places decimal precision
    #typing pi  & pressing return puts 3.141
   type(pi)
=> <type 'float'>
    pi = 3.1415
   type(pi)
=> <type 'float'>
    #pi puts 3.1415000000000002
Run Code Online (Sandbox Code Playgroud)

好的浮点精度因为不精确而臭名昭着; 但为什么只有4点精度得到那个"尾巴"呢?

也:

 pi2 = 3.1415100000000002
 pi == pi2 # pi was assigned 3.1415
 => True
 print(pi2)
 3.14151 # Where's my precision? 
Run Code Online (Sandbox Code Playgroud)

Bri*_*and 4

整数和浮点数被赋予一定数量的位数。对于整数,每一位对应于 2 的幂。第一个数字是 2 0,然后是 2 1、2 2,依此类推。因此,为了存储整数,5我们有2 0 + 2 2 = 1 + 4

对于浮点数,我们将它们存储为两部分。指数和小数。如果小数为 0.75,指数为 2,则为0.75 * 10 2 = 7.5。小数存储为 2 的负幂。因此我们有 2 -1、 2 -2。2 -3。等。这些相当于.5.25.125等。

有些数字无法存储,因为它们实际上需要无限位来表示,例如 0.1,而其他数字(例如 3.1415)需要比 CPU 为浮点数提供的位数更多的位(24 是 32 位浮点数的标准,但算法有所不同)。

比较浮点数的正确方法是定义方差,并按照这些思路使用一些东西。

variance = .0001
floatsEqual = lambda f1, f2: f1 - variance <= f2 and f1 + variance >= f2

if (floatsEqual(3.1415, 3.1415 + 1 - 1)):
    pass
Run Code Online (Sandbox Code Playgroud)

在Python中,decimal库也很有用。