I am trying to plot some non-linear graphs (x vs x raised to some power). However, the output on y-axis gets messed up once I reach x^5 or greator.
I have tried increasing the plot size and manually setting y limits but to no avail.
I have written the following code.
plt.figure(figsize=(14, 7))
for i in range (1, 10):
plt.subplot(3,3,i)
plt.plot(x, x**i, alpha=0.5)
plt.title(f'x^{i}')
ax.set_xlim([np.min(x), np.max(x)])
ax.set_ylim([np.min(x**i), np.max(x**i)])
plt.show()
It appears that your array x
is of the type int32
, causing an overflow. You can verify this by checking what x.dtype
returns.
Unlike the built-in Python int
's with infinite precision, int32
only has 32 bits of precision, and since it's signed it ranges from -(2^31) to (2^31)-1 or −2,147,483,648 to 2,147,483,647. From your graphs, the weirdness begins around 75^5=2,373,046,875. This is larger than the largest number your datatype can represent, and therefore you get overflow.
The easiest remedy is simply to operate on another datatype, int64
would suffice although I'd recommend working with floats if you are dealing with large numbers. You can cast x
to use int64
by x = x.astype("int64")
.