# Python3.7官方向导翻译之Python浮点数运算

import math
format(math.pi, '.12g')                  # give 12 significant digits
'3.14159265359'

format(math.pi, '.2f')                   # give 2 digits after the point
'3.14'

repr(math.pi)
'3.141592653589793'


.1 + .1 + .1
0.30000000000000004


round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1)
False


round(.1 + .1 +.1, 10) == round(.3, 10)
True


Python提供的工具可以帮助您在罕见的情况下确实知道浮点数的确切值。 float.as_integer_ratio（）方法将float的值表示为一个分数：

x = 3.14159
x.as_integer_ratio()
(3537115888337719, 1125899906842624)


x == 3537115888337719 / 1125899906842624
True


float.hex（）方法以十六进制表示浮点数（基数为16），同样给出计算机存储的确切值：

x.hex()
'0x1.921f9f01b866ep+1'


x == float.fromhex('0x1.921f9f01b866ep+1')
True


sum([0.1] * 10) == 1.0
False

math.fsum([0.1] * 10) == 1.0
True


### 表示错误

2**52 <=  2**56 // 10  < 2**53
True


q, r = divmod(2**56, 10)
r
6


q+1
7205759403792794


0.1 * 2 ** 55
3602879701896397.0


3602879701896397 * 10 ** 55 // 2 ** 55
1000000000000000055511151231257827021181583404541015625


format(0.1, '.17f')
'0.10000000000000001'


fraction和decimal模块让这些计算更简单：

from decimal import Decimal
from fractions import Fraction
Fraction.from_float(0.1)
Fraction(3602879701896397, 36028797018963968)

(0.1).as_integer_ratio()
(3602879701896397, 36028797018963968)

Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')

format(Decimal.from_float(0.1), '.17')
'0.10000000000000001'

11-23
12-07 2万+

08-03 1731
06-14 3091
06-14 1849
06-13 1226
06-17 1038