Python 绘制函数的函数

Python function that plots functions

我目前正在尝试在 python 中定义一个绘制函数的函数。

我已经完成了这个:

def plota_f(x0, xf, n):
  xpoints = []
  ypoints = []
  for i in range(0,n):
      xpoints.append(x0+(xf-x0)/n *i)
      ypoints.append(np.sin(x0+(xf-x0)/n *i))
  plt.plot(xpoints, ypoints)
  plt.show()

用 n 步绘制从 x0 到 xf 的 Sin 函数,但我希望能够添加参数 f

def plota_f(f,x0,xf,n):

这样我就可以打电话了

plota_f(x**2,0,10,100)

并绘制二次函数或调用

plota_f(np.sin(x),0,10,100)

并绘制正弦函数。有简单的方法吗?


编辑:这是我回答后得到的代码

def plota_f(f,x0,xf,n):
xpoints = []
ypoints = []
for i in range(0,n):
    xpoints.append(x0+(xf-x0)/n *i)
    x=x0+(xf-x0)/n *i
    ypoints.append(eval(f))
plt.plot(xpoints, ypoints)
plt.show()

使用 numpy 非常简单:

from x0 to xf with n steps

这是np.linspace

的定义

be able to add a parameter f

使用 lambda 函数

演示:

def plota_f(f, x0, xf, n):
    # Use with caution, eval can be dangerous
    xpoints = np.linspace(x0, xf, n, endpoint=True)
    ypoints = eval(f)
    plt.plot(xpoints, ypoints)
    plt.show()

plota_f('x**2', 0, 10, 100)

你是over-complicating问题所在。这是我如何在某个时间间隔内绘制频率为 f 的正弦函数,比如从 t0t1,步长为 n

t = np.linspace(t0, t1, n)
fn = np.sin(2 * np.pi * f * t)
plt.plot(t, fn)

当您将域值与函数值分开时,您可以看到一条前进的道路。例如,您可以定义这样的函数:

def my_sin(f):
    def func(t):
        return np.sin(2 * np.pi * f * t)
    return func

现在你可以做这样的事情了:

def plot_func(func, t0, t1, n):
    t = np.linspace(t0, t1, n)
    plt.plot(t, func(t))

您只需定义接受单个参数 t 的函数,该参数是您要评估的点的数组:

def my_quad(a, b, c):
    def func(t):
        return a * t**2 + b * t + c
    return func

plot_func(my_sin(10), -10, 10, 1000)
plot_func(my_quad(3, 0, 0), -5, 5, 100)