Search code examples
pythondiscrete-mathematics

How to plot tan(x) with pyplot and numpy


Code:

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10000)
plt.plot(x, np.tan(x))
plt.show()

Expected result:

enter image description here

The result I get:

enter image description here


Solution

  • There are two issues, I think. The first is about np.linspace, the second about plotting.

    np.linspace defaults to returning 50 elements within the given range. So you're plotting 50 points over (0, 10000), meaning the elements are very widely spaced. Also, that range doesn't make a whole lot of sense for the tangent function. I'd use something much smaller, probably +/- 2 * pi.

    The second issue is the y-axis. The tangent function diverges to infinity quite quickly at multiples of pi/2, which means you're missing a lot of the interesting behavior by plotting the full y-range. The code below should solve these issues.

    x = np.linspace(-2 * np.pi, 2 * np.pi, 1000)
    plt.plot(x, np.tan(x))
    plt.ylim(-5, 5)
    

    You should see something like this: enter image description here