如何访问未存储在浮点值中的十进制数
How to access the decimal numbers which are not stored in float value
如果我想访问数字 1/919 的小数点后第 100 位,有什么办法吗?
我知道浮动值只存储到某些小数点,所以我只能访问存储的小数点但如何访问未存储的小数点
您的直觉是正确的。 Python 将浮点数存储为 64 位浮点值,don't have the precision 输出到 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))
如果我想访问数字 1/919 的小数点后第 100 位,有什么办法吗? 我知道浮动值只存储到某些小数点,所以我只能访问存储的小数点但如何访问未存储的小数点
您的直觉是正确的。 Python 将浮点数存储为 64 位浮点值,don't have the precision 输出到 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))