2

The last cell of the bellow array shows a wrong result:

Code:

import numpy
b=numpy.array ([[1,2,3,4],[5,6,8,16]])
b=b**b/b+1
b

result:

array([[2.000000e+00, 3.000000e+00, 1.000000e+01, 6.500000e+01],
       [6.260000e+02, 7.777000e+03, 2.097153e+06, 1.000000e+00]])

All numbers are correct except for the last one.

Type is numpy.float64. The correct answer is 1.152921504606847e+18.

Any ideas?

Thanks

1 Answer 1

7

When you construct a numpy array with whole numbers, its type will be int32 or int64 depending on your system, instead of the float64 you expected. So when you do 16**16, the result overflowed and you end up with a 0.

To fix this, specify the float64 type for your numpy array, like this:

b=numpy.array ([[1,2,3,4],[5,6,8,16]], dtype='float64')

Or if you want, add a .0 to any of the numbers in your array to specify that you want to use float not int.

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

3 Comments

To add to it, I think the default is int64 and if you want to check, overflow happens since np.iinfo(np.int64).max/(16**16) is smaller than one.
Actually, the dtype will be some integer dtype, but the exact size is platform-dependant, so whether it is a 64 bit vs a 32 bit architecture and the OS as well. Basically, it is whatever a C long is. Assuming a 64bit operating system, that is a 64bit integer on Linux, but a 32 bit integer on windows.
Also, you should just do numpy.array([[1,2,3,4],[5,6,8,16]], dtype=numpy.float64)

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.