[issue3439] math.frexp and obtaining the bit size of a large integer

Fredrik Johansson report at bugs.python.org
Thu Jul 24 19:20:44 CEST 2008


New submission from Fredrik Johansson <fredrik.johansson at gmail.com>:

Python 3.0b2 (r30b2:65106, Jul 18 2008, 18:44:17) [MSC v.1500 32 bit
(Intel)] on
 win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.frexp(10**100)
(0.5714936956411375, 333)
>>> math.frexp(10**1000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C double
>>>

(Same behavior in Python 2.5.2, and presumably 2.6 although I haven't
checked the latter.)

I think it should be easy to make frexp work for large integers by
calling PyLong_AsScaledDouble and adding the exponents. It would be
logical to fix this since math.log(n) already works for large integers.

My reason for requesting this change is that math.frexp is the fastest
way I know of to accurately count the number of bits in a Python integer
(it is more robust than math.log(n,2) and makes it easy to verify that
the computed size is exact) and this is something I need to do a lot.

Actually, it would be even more useful to have a standard function to
directly obtain the bit size of an integer. If I'm not mistaken,
PyLong_NumBits does precisely this, and would just have to be wrapped.
Aside from my own needs (which don't reflect those of the Python
community), there is at least one place in the standard library where
this would be useful: decimal.py contains an inefficient implementation
(_nbits) that could removed.

----------
components: Library (Lib)
messages: 70216
nosy: fredrikj
severity: normal
status: open
title: math.frexp and obtaining the bit size of a large integer
type: feature request
versions: Python 2.6, Python 3.0

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue3439>
_______________________________________


More information about the Python-bugs-list mailing list