Strange np.sqrt behavior for large integers

>>> np.__version__ '1.7.0' >>> np.sqrt(10000000000000000000) 3162277660.1683793 >>> np.sqrt(100000000000000000000.) 10000000000.0 >>> np.sqrt(100000000000000000000) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: sqrt 

Huh ... AttributeError: sqrt what is happening here? math.sqrt does not seem to have the same problem.

+7
source share
1 answer

The final number is long (the Python name for an arbitrary precision integer), which NumPy apparently can't handle:

 >>> type(100000000000000000000) <type 'long'> >>> type(np.int(100000000000000000000)) <type 'long'> >>> np.int64(100000000000000000000) Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: Python int too large to convert to C long 

AttributeError occurs because NumPy, seeing a type that does not know how to handle, by default calls the sqrt method of the object; but this does not exist. So this is not numpy.sqrt , which is missing, but long.sqrt .

In contrast, math.sqrt knows about long . If you are going to deal with very large numbers in NumPy, use floats when possible.

EDIT : Well, you are using Python 3. While the difference between int and long has disappeared in this version, NumPy is still sensitive to the difference between PyLongObject , which can be successfully converted to C long using PyLong_AsLong and one that cannot.

+8
source

All Articles