pythonnumpymatplotlib

Exponential plot in python is a curve with multiple inflection points instead of exponential


I am trying to draw a simple exponential in python. When using the code below, everything works fine and the exponential is shown

import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import numpy as np

def graph(func, x_range):
x = np.arange(*x_range)
y = func(x)
plt.plot(x, y)

graph(lambda x: pow(3,x), (0,20))

plt.savefig("mygraph.png")

However if I change the range from 20 to 30, it draws a curve which is not exponential at all.

enter image description here

Why is that happening?


Solution

  • I can't make time to nail this now, but the graph looks a whole lot like what I'd expect if integer arithmetic is overflowing. numpy's ints are fixed-width, unlike Python's ints (which are unbounded).

    In particular,

    >>> 3**20
    3486784401
    >>> _.bit_length()
    32
    

    so at the point things start to go crazy the result is overflowing a 32-bit int. Try replacing the 3 with 3.0 in your pow(3,x)?