Python 浮点数运算
Python 浮点数运算
rainyear 发表于2年前
Python 浮点数运算
• 发表于 2年前
• 阅读 107
• 收藏 7
• 评论 0

0.1 == 0.10000000000000000000001

True

0.1+0.1+0.1 == 0.3

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$$

(0.1).as_integer_ratio()

(3602879701896397, 36028797018963968)


(0.10000000000000001).as_integer_ratio()

(3602879701896397, 36028797018963968)


print(0.10000000000000001)

0.1


### 浮点数运算

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

(1351079888211149, 4503599627370496)
(5404319552844595, 18014398509481984)
False


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

True


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

False
True


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

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

False

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


×