Skip to content

math.log handles int but not 3rd party integer types #120950

Open
@oscarbenjamin

Description

@oscarbenjamin

Bug report

Bug description:

The math.log function has a special path for integers that only works for the builtin int type:

cpython/Modules/mathmodule.c

Lines 2220 to 2223 in ac61d58

loghelper(PyObject* arg, double (*func)(double))
{
/* If it is int, do it ourselves. */
if (PyLong_Check(arg)) {

That means that it does not work for 3rd party integer types e.g.:

In [9]: n = gmpy2.mpz(10)**1000

In [10]: math.log(int(n))
Out[10]: 2302.585092994045

In [12]: math.log(operator.index(n))
Out[12]: 2302.585092994045

In [11]: math.log(n)
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
Cell In[11], line 1
----> 1 math.log(n)

OverflowError: 'mpz' too large to convert to float

Maybe if there is a special integer handling path in math.log it should check for __index__ before __float__.

Related gh-106502 is about math.log with Decimal.

CPython versions tested on:

3.13

Operating systems tested on:

No response

Linked PRs

Metadata

Metadata

Labels

extension-modulesC modules in the Modules dirtype-featureA feature request or enhancement

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions