Here I have a 1D array:
JavaScript
x
10
10
1
>>> import numpy as np
2
>>> a = np.array([75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328,
3
75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328,
4
75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328,
5
75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328,
6
75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328,
7
75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328,
8
75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328,
9
75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328])
10
And the sum of all elements in the array should be 75491328*8*8 = 4831444992
. However, when I use np.sum
, I get a different output.
JavaScript
1
3
1
>>> np.sum(a)
2
536477696
3
That’s what happens on my Jupyter Notebook using the latest version of Numpy. But when I use Jupyter Notebook of Coursera using old version 1.18.4 of Numpy, everything is fine.
How can I fix this bug? Is it a bug or is it because of me?
Advertisement
Answer
The problem is caused by integer overflow, you should change the datatype of np.array
to int64
.
JavaScript
1
3
1
import numpy as np
2
np.array([Your values here], dtype=np.int64)
3