简体   繁体   English

Python中的精确math.log(x,2)

[英]Precise math.log(x, 2) in Python

In python, I need to get the rounded down logarithm of positive integers for base 2, including big numbers. 在python中,我需要得到基数为2的正整数的向下舍入,包括大数。

However, since floating point math is used, I might get bad results, for example: 但是,由于使用了浮点数学,我可能会得到不好的结果,例如:

>>> import math
>>> int(math.log(281474976710655, 2))
48

However: 然而:

>>> 2 ** 48
281474976710656

So the correct result, rounded down, should be 47. 因此,向下舍入的正确结果应为47。

How can I get the correct value? 我怎样才能得到正确的价值?

In Python 3, integers have a .bit_length method, so you should use that to get your rounded down base 2 logarithm. 在Python 3中,整数有一个.bit_length方法,所以你应该使用它来得到你的舍入基数2对数。

Here's a short demo: 这是一个简短的演示:

m = 2 ** 1000
for n in (281474976710655, m-1, m, m+1):
    a = n.bit_length() - 1
    b = 2 ** a
    print(a, b <= n < 2 * b)

output 产量

47 True
999 True
1000 True
1000 True

In python 3 int s even have an efficient .bit_length() method! 在python 3 int甚至有一个高效的.bit_length()方法!

>>> (281474976710655).bit_length()
48
>>> (281474976710656).bit_length()
49

In python 2, instead of using floating point math, count the number of bits: 在python 2中,不使用浮点数学,而是计算位数:

def log2(n):
    assert n >= 1
    return len(bin(n)) - 3  # bin() returns a string starting with '0b'

( Edited following this comment ) (在此评论后 编辑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM