## Python 浮点数运算



In [1]:

0.1 == 0.10000000000000000000001




Out[1]:

True




In [2]:

0.1+0.1+0.1 == 0.3




Out[2]:

False



### IEEE 浮点数表示法

1.234 = 1 + 1/10 + 2/100 + 3/1000

$$d = \sum_{i=-n}^m10^i*d_i$$

1.001 = 1 + 0/2 + 0/4 + 1/8

$$d = \sum_{i=-n}^m2^i*d_i$$

$$d = s * \sum_{i=-52}^{11} 2^i*d_i$$



In [3]:

(0.1).as_integer_ratio()




Out[3]:

(3602879701896397, 36028797018963968)





In [4]:

(0.10000000000000001).as_integer_ratio()




Out[4]:

(3602879701896397, 36028797018963968)





In [5]:

print(0.10000000000000001)




0.1



### 浮点数运算



In [6]:

a = .1 + .1 + .1
b = .3
print(a.as_integer_ratio())
print(b.as_integer_ratio())
print(a == b)




(1351079888211149, 4503599627370496)
(5404319552844595, 18014398509481984)
False





In [7]:

round(a, 10) == round(b, 10)




Out[7]:

True





In [8]:

print(round(a, 17) == round(b, 17))
print(round(0.1, 1) == round(0.111, 1))




False
True



Python 中使用更精确的浮点数可以通过 decimalfractions 两个模块，从名字上也能猜到，decimal 表示完整的小数，而 fractions 通过分数的形式表示小数：



In [9]:

from decimal import Decimal
a = Decimal(0.1)
b = Decimal(0.1000000000000001)
c = Decimal(0.10000000000000001)
print(a)
print(b)
print(c)

a == b == c




0.1000000000000000055511151231257827021181583404541015625
0.10000000000000010269562977782697998918592929840087890625
0.1000000000000000055511151231257827021181583404541015625

Out[9]:

False




In [10]:

from fractions import Fraction
f1 = Fraction(1, 10) # 0.1
print(float(f1))
f3 = Fraction(3, 10) # 0.3
print(float(f3))

print(f1 + f1 + f1 == f3)




0.1
0.3
True