我需要绘制一个间隔上定义的简单函数的图。
import numpy as np
from matplotlib import pylab as plt
def sqr(x, n=2):
return float(x ** n)
def get_plot(func, xs, n):
ys = []
for x in xs:
ys.append(func(x, n))
ys = np.array(ys)
plt.plot(xs, ys)
xs = np.arange(1.0, 30., 0.01)
get_plot(sqr, xs, 4)
但这给了我typeError:
TypeError: get_plot() takes exactly 2 arguments (3 given)
答案 0 :(得分:0)
除了函数名称中的拼写错误外,一旦添加完所有函数,就应该将列表转换为for循环之外的数组。此外,我不明白为什么只对NumPy数组xs
像ys=xs**4
那样使用向量化操作
import numpy as np
from matplotlib import pylab as plt
def sqr(x, n=2):
return float(x ** n)
def get_plot(func, xs, n):
ys = []
for x in xs:
ys.append(func(x, n))
ys = np.array(ys) # <-- moved outside the for loop
plt.plot(xs, ys)
xs = np.arange(1.0, 30., 0.01)
get_plot(sqr, xs, 4)