what's the reasonale of loghelper() in mathmodule.c

Mark Dickinson dickinsm at gmail.com
Wed Apr 9 15:11:48 CEST 2008

On Apr 9, 4:38 am, rockins <ybc2... at gmail.com> wrote:
> I cannot understand it well, can anyone explain me why and how
> loghelper() can compute any base logarithm? Or could anyone give me
> some reference(such as, books or papers)?

loghelper is there so that log(n) can be computed for any positive
integer n---it's nothing to do with computing logs to an arbitrary

All of the other math functions convert an integer argument to a float
first.  That conversion fails if the integer is larger than the
representable float (around 1.7e308 on most systems).  For example:

>>> from math import sqrt, log
>>> sqrt(10**600)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: long int too large to convert to float
>>> log(10**600)

The sqrt call first tries to convert 10**600 to a float, giving an
OverflowError (even though the actual square root *is* representable
as a float).  The log call goes through loghelper instead, which
doesn't try to convert 10**600 to a float, but instead computes
the log based on the top few bits of 10**600 (in its internal
binary representation) and on the number of bits required to
represent 10**600.

You're not going to learn much about math function implementations
from mathmodule.c:  all it does it wrap the platform libm functions.


More information about the Python-list mailing list