On 29/1/19 9:22 am, Yuping Wang wrote:
Dear Nmupy developers and users:
I am a new user of Numpy ,I have encountered a question about
Numpy recently, which need your help. The question is below:
I don know why there are negative numbers
can somebody explain to me why these happens
Thanks in advance!
NumPy ndarrays are typed. Since you do not specify a type in arange,
numpy assumes you want `a` to be the type of 2000. I assume you are on a
system where numpy converts 2000 to an `int32`, so if you ask what is
the type of a: (`a.dtype`) it will show `int32`, meaning the values in a
are interpreted as if they are 32 bit integers.
2000*2000*2000 overflows a 32 bit signed integer, so it wraps around to
a negative value.
The way around this is to specify what type you wish to use:
`a=np.arange(2000, dtype=float)**3` or `a=np.arange(2000,
dtype='int64`)**3 will not overflow. For floats, most CPUs/compilers
provide an indication when float values overflow, so we can raise a
warning appropriately. Unfortunately, detecting overflows with ints has
no hardware support, so adding a warning would mean checking each value
before a calculation, causing an unacceptable slow down.
Where did you start learning about NumPy? Perhaps you could suggest they
add this explanation (or if it is in our documentation point out where
you think would be appropriate) since it seems many people have problems
with dtypes and overflow.
Matti
_______________________________________________
NumPy-Discussion mailing list
NumPy-Discussion@python.org
https://mail.python.org/mailman/listinfo/numpy-discussion