【问题标题】:Wrong output for math.logmath.log 的错误输出
【发布时间】:2020-01-10 08:37:09
【问题描述】:

我正在尝试计算最接近的 2^n 到一个非常大的数字(

我尝试使用 math.log(number,2)。但这对于非常大的数字给出了错误的结果。如果不使用其他库,我应该如何做到这一点?

a = 9843649374639837463  # a is any num between 1 and 10^9
number = int(math.log(a,2))

【问题讨论】:

标签: python python-3.x floating-point precision logarithm


【解决方案1】:

大整数输入被转换为精度有限的浮点数,因此 some input precision is being lost。此外,math.log2() 可能比 math.log() 更准确,因为它针对基数 2 进行了微调。

有一个 int 方法会非常准确,bit_length():

>>> a = 9843649374639837463
>>> a.bit_length()
64
>>> bin(a)
'0b1000100010011011101010101111001111001100111001110101000100010111'

注意,浮点日志非常接近但不准确:

>>> a = 9843649374639837463
>>> 2.0 ** math.log2(a)
9.843649374639845e+18
>>> abs(a - 2.0 ** math.log2(a))
8192.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2022-11-26
    相关资源
    最近更新 更多