【问题标题】:How to access the decimal numbers which are not stored in float value如何访问未存储在浮点值中的十进制数
【发布时间】:2021-01-07 09:36:09
【问题描述】:

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

【问题讨论】:

    标签: python numbers decimal


    【解决方案1】:

    你的直觉是正确的。 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))
    

    【讨论】:

    • 所以如果我想说访问第 100 位,我可以这样做吗?这不会存储大量数据吗?
    • 你可以改变精度。 decimal 使用与基数、符号和指数的 IEEE 754 浮点数相同的想法,它们只支持与 IEEE 754 不同的任意精度。因此,要提取第 n 个数字,您仍然必须进行与 str() 相同的转换运行。
    猜你喜欢
    • 2014-01-06
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 2020-07-01
    • 1970-01-01
    相关资源
    最近更新 更多