当修剪由于分割导致的大小数时,我遇到溢出问题。例如。:
>>> from math import floor
>>> int(100000000000000123.1)
100000000000000128
>>> floor(100000000000000123.1)
100000000000000128
从类型看来,数字是一个普通的浮点数,它不能以所需的精度存储。所以即使使用floor()我也会遇到同样的问题。是否有更好的数据类型来存储'长浮点/双打'?如果是的话,我如何强制bigints的划分不返回低精度浮点数?顺便说一句,我使用的是Python 3.6 64位。
你想要stdlib模块decimal
import decimal
long_number = '100000000000000123.1' # note that this is a string
your_decimal = decimal.Decimal(long_number)
Decimal
s非常聪明,可以从任何标准的数学运算中返回Decimal
对象
result = your_decimal - 123
assert isinstance(result, decimal.Decimal)
assert your_decimal == decimal.Decimal('100000000000000000.1')