如何访问未存储在浮点值中的十进制数



如果我想访问数字1/919的第100个小数点,有办法吗?我知道浮动值只能存储到某些小数,所以我只能访问存储的小数,但如何访问未存储的小数

你的直觉是正确的。Python将浮点值存储为64位浮点值,其精度无法达到100位小数。您必须使用decimal软件包,并根据需要设置精度。

import decimal
# calculate up to 120 decimals
decimal.get_context().prec = 120
result = decimal.Decimal(1) / decimal.Decimal(919)
print(result)

# pull an arbitrary digit out of the string representation of the result
def get_decimal_digit(num, index):
# find where the decimal points start
point = str(num).rfind('.')
return int(str(num)[index + point + 1])
# get the 100th decimal
print(get_decimal_digit(result, 100))

最新更新