lei37927
lei37927

Reputation: 31

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.

Output image

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?

Upvotes: 3

Views: 198

Answers (3)

delta
delta

Reputation: 3818

Data type in numpy is different than it in Python. It gets overflowed, as it is int in C.

Upvotes: 0

Stephen Mylabathula
Stephen Mylabathula

Reputation: 398

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))

Upvotes: 1

Ishan
Ishan

Reputation: 1339

np.arange() sets dtype of x[i] as int64 which overflows for large values. list(range(1,21)) would work.

Upvotes: 0

Related Questions