简体   繁体   中英

python isn't plotting the “tangent” function correctly

I'm trying to plot the general tangent function onto matplotlib in Python but it is coming out incorrectly.

The function I'm trying to plot is: $$ f(x) = A tan( \\frac{2\\pi}{\\lambda} x - \\phi ) $$


import numpy as np
import math
import matplotlib.pyplot as plt
import tkinter

f = lambda x, A, lambda_, phi: A * math.sin( ((2 * math.pi) / lambda_) * x - phi)
g = lambda x, A, lambda_, phi: A * math.cos( ((2 * math.pi) / lambda_) * x - phi)
h = lambda x, A, lambda_, phi: f(x, A, lambda_, phi) / g(x, A, lambda_, phi)

def generate_graph(A, lambda_, Phi):
    plt.figure()
    x = np.arange(-.95, .95, 0.005)
    #plt.plot(x, [f(k, A, lambda_, Phi) for k in x], color='red')
    #plt.plot(x, [g(k, A, lambda_, Phi) for k in x], color='blue')
    plt.plt(x, [h(k, A, lambda_, Phi) for k in x], color='green')
    plt.show()

A = 1 #amplitude
lambda_ = 3 #wavelength
Phi = 0 #phase shift

generate_graph(A, lambda_, Phi)

It's supposed to look like this: 正确

But it ends up looking like this: 错误

This happens due to singularities of the tangent function (ie, having x values around those points). A quick fix would be to restrict the y-axis with, eg,

plt.ylim(-40, 40)

giving

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM