3

Today I decided to write simple program in Python, just to practice before exam. Firstly, I wanted to draw sin and cos plot, which wasn't so hard. But then, I decided to challenge myself and draw tangent plot.

import pylab as p

x= p.arange(-1.0,1.0,0.1)
y= (p.sin(2*p.pi*x)) / (p.cos(2*p.pi*x))

p.plot(x,y,'g-',lw=1)
p.show()

It returns... ugh... this:

enter image description here

As you can see, it looks more like ECK plot than tangent plot. Does anyone knows what's wrong?

MackM
  • 2,511
  • 4
  • 29
  • 40
Szczepenson
  • 45
  • 1
  • 5
  • 1
    try reducing the step size. – M4rtini Jan 18 '14 at 13:31
  • basically python is trying to draw a continuous graph given a set of points, but the tangent is not continuous everytwhere. You should, either treat the discontinuities (pi/2, 3pi/2 ...) with special care or... use draw only the points but not the lines connecting them – Manuel Pena Aug 20 '18 at 04:22

2 Answers2

4

If you increase the number of points in x,

import pylab as p
import numpy as np
x = p.linspace(-1.0, 1.0, 1000)
y = (p.sin(2 * p.pi * x)) / (p.cos(2 * p.pi * x))
p.plot(x, y, 'g-', lw=1)
p.show()

you get something like this: enter image description here

Notice how large the y-range is getting. Matplotlib is not able to show you much of the small values in the tangent curve because the range is so large.

The plot can be improved by ignoring the extremely large values near the asymptotes. Using Paul's workaround to handle asymptotes,

import pylab as p
import numpy as np
x = p.linspace(-1.0, 1.0, 1000)
y = (p.sin(2 * p.pi * x)) / (p.cos(2 * p.pi * x))

tol = 10
y[y > tol] = np.nan
y[y < -tol] = np.nan

p.plot(x, y, 'g-', lw=1)
p.show()

you get

enter image description here

Community
  • 1
  • 1
unutbu
  • 711,858
  • 148
  • 1,594
  • 1,547
4
import pylab as p

x= p.arange(-1.0,1.0,0.01)  # <- 0.01 step size.
y= (p.sin(2*p.pi*x)) / (p.cos(2*p.pi*x))
# y = p.tan(2*p.pi*x)
p.plot(x,y,'g-',lw=1)
p.ylim([-4, 4]) # <- Restricting the ylim so we don't see the ~inf values. 
p.show()

This will be the result if you don't set ylim. (the values approach infinity)

Result without setting ylim

Result with setting ylim.

Result

M4rtini
  • 11,714
  • 3
  • 31
  • 41