Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Python, why is y**2 sometimes incorrect when y is a numpy array?

First I compute a square in the IDLE shell of Python 3.12.0:

>>> x = 123456
>>> x**2
15241383936

This agrees with my TI-89. Now I compute what I would think would be the same square using numpy arrays:

>>> import numpy as np
>>> y = np.array([x])
>>> ysqr = y**2
array([-1938485248])
>>> ysqr[0]  
-1938485248

What is going on here? Why aren’t x**2 and ysqr[0] equal?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

x is of type int, which is unbounded in Python and thus x**2, which is also an int can reach arbitrarily high value.

However, y is a numpy array with a specific data type. We can observe its data type with print(y.dtype) and see that it’s np.int32. Using np.iinfo(np.int32), we can see the following: iinfo(min=-2147483648, max=2147483647, dtype=int32).

Since 15241383936 is larger than the max value of int32, it overflows and starts counting up from -2147483648. In fact, it is so large, it cycles through to 2147483647 and does this multiple times until it finally lands on -1938485248

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading