Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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?

like image 406
Mike Dewar Avatar asked May 17 '11 14:05

Mike Dewar


People also ask

What does NumPy log do?

Python's numpy. log() is a mathematical function that computes the natural logarithm of an input array's elements. The natural logarithm is the inverse of the exponential function, such that log (exp(x)) = x.

How do you use log in NumPy?

log() in Python. The numpy. log() is a mathematical function that helps user to calculate Natural logarithm of x where x belongs to all the input array elements. Natural logarithm log is the inverse of the exp(), so that log(exp(x)) = x.

Why NumPy array operations are faster than looping?

NumPy Arrays are faster than Python Lists because of the following reasons: An array is a collection of homogeneous data-types that are stored in contiguous memory locations. On the other hand, a list in Python is a collection of heterogeneous data types stored in non-contiguous memory locations.


2 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.

like image 107
Robert Kern Avatar answered Oct 11 '22 21:10

Robert Kern


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

like image 37
florent Avatar answered Oct 11 '22 19:10

florent