28

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?

2
  • 4
    I suppose NumPy first tries to convert the argument to one of its scalar types and then tries to access some NumPy-specific attribute. math.factorial(21) excedes the size of numpy.uint64, so it can't be converted to a NumPy scalar. Of course NumPy should throw a ValueError! Commented May 17, 2011 at 15:05
  • See also AttributeError in python/numpy when constructing function for certain values Commented Jul 2, 2016 at 8:30

2 Answers 2

33

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, this explains a lot of things
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.