我目前正在尝试在 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()
绘制从 x0 到 xf 的 Sin 函数,共 n 个步骤,但我希望能够添加参数 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)
关于绘制函数图的 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70974321/