I'm trying to map a simple quadratic function, where zs is a numpy array and R is a constant
Ns = -np.square(zs) + 2*zs*R+ 3*R**2
It works fine most of the time, but for some reason whenever I have the evaluation set up as following the code breaks:
>>>zs = np.array(range(80262,80268)
>>>R = 26756
>>>Ns = -np.square(zs) + 2*zs*R+ 3*R**2
>>>print Ns
array([ 642108, 535095, 428080, 321063, 214044
4295074319], dtype=int64)
That last value in the array should be 107023. Whenever I go above 80267, the squaring function breaks completely and starts giving me absolutely ridiculous answers. Is this just a data type error, or is something else going on here that I don't know about?
The trouble is that
zs = np.array(range(80262,80268))creates an array ofint32values.np.square(zs)returns an array of the same datatype aszsand the final squared value in the array overflows the four bytes of memory it's been allocated.You see that
Ns = -np.square(zs) + 2*zs*R+ 3*R**2has a datatype ofint64because NumPy has given this array more memory in order to accommodate the larger numbers. However, it's too late: you already have an overflowed value innp.square(zs).To solve the issue, create
zsusing thenp.int64datatype:Be aware that the same problem will occur again if the numbers in
zsget large enough!