'Python is acting weird with math calculations, why did this happen?
I was bored today, so I started to write some few-minutes codes to pass the time. Anyway I wanted to see what is the functional relationship between x to the power of x and x itself, so I wrote the following codes.
x = np.arange(1,21,1)
y = []
for i in x:
y.append(len(str(i**i)))
plt.plot(x,y,'b')
That seems quite simple and absolutely impossible to go wrong, right? There is no error indeed, but the output image is like this.
That is so strange, so I wrote the following codes to verify, print(len(str(20**20))) but this was normal and gave me the result of 27.
It stands to reason that the curve of this function should soar all the way, but it has serious problems at 16 and 20. Is this a Python problem? Why did this happen?
Solution 1:[1]
Good question - the data type of the values in x are np.int64. You are overflowing 64-bits when you perform 16**16. Python's intrinsic int data type has no such limit though. So you should either cast your data as int before conversion:
y.append(len(str(int(i)**int(i))))
or define x as an int array:
x = list(range(1, 21))
Solution 2:[2]
np.arange() sets dtype of x[i] as int64 which overflows for large values. list(range(1,21)) would work.
Solution 3:[3]
Data type in numpy is different than it in Python.
It gets overflowed, as it is int in C.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stephen Mylabathula |
| Solution 2 | Ishan |
| Solution 3 | delta |

