[issue9959] int(math.log(4,2)) == 1 instead of 2
akira
report at bugs.python.org
Mon Sep 27 20:14:24 CEST 2010
akira <4kir4.1i at gmail.com> added the comment:
> No, it's not really a bug: math.log(x, 2) isn't an atomic operation:
It is not a bug, but values of math.log(4) differs between 3.1 and 3.2
i.e., math.log(4.0) in 3.2 returns value that is consistent with
math.log(4) in 3.1 but math.log(4) in 3.2 doesn't.
> I'm not sure what you're using math.log(x, 2) for, but you may be
interested in the int.bit_length method.
The docs for int.bit_length say:
> if x is nonzero, then x.bit_length() is the unique positive integer
k such that 2**(k-1) <= abs(x) < 2**k. Equivalently, when abs(x) is
small enough to have a correctly rounded logarithm, then k = 1 +
int(log(abs(x), 2)).
It is expected that int(log(n,2)) produces correct result for small n.
> Having said that, it would be possible to improve the algorithm
that's used to compute log of an integer (see the loghelper function
in Modules/mathmodule.c): currently, for positive k, log(2**k) ends
up being computed as log(0.5) + (k+1)*log(2), which doesn't help; it
would be slightly better if it were computed directly as k*log(2)
instead. But you still can't (and shouldn't) rely on log(x, 2)
giving exact results for powers of 2.
I've changed loghelper() to return improved result for power of 2
----------
keywords: +patch
Added file: http://bugs.python.org/file19030/math_log_power_two.diff
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue9959>
_______________________________________
More information about the Python-bugs-list
mailing list