python+numpy: why does numpy.log throw an attribute error if its operand is too big?

Question:

Running

np.log(math.factorial(21))

throws an AttributeError: log. Why is that? I could imagine a ValueError, or some sort of UseYourHighSchoolMathsError, but why the attribute error?

Asked By: Mike Dewar

||

Answers:

The result of math.factorial(21) is a Python long. numpy cannot convert it to one of its numeric types, so it leaves it as dtype=object. The way that unary ufuncs work for object arrays is that they simply try to call a method of the same name on the object. E.g.

np.log(np.array([x], dtype=object)) <-> np.array([x.log()], dtype=object)

Since there is no .log() method on a Python long, you get the AttributeError.

Answered By: Robert Kern

Prefer the math.log() function, that does the job even on long integers.

Answered By: florent
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.