我有一个函数
np.sin(x / 2.) * np.exp(x / 4.) + 6. * np.exp(-x / 4.)
我可以使用下面的代码来绘制它:
x = np.arange(-5, 15, 2)
y = np.sin(x / 2.) * np.exp(x / 4.) + 6. * np.exp(-x / 4.)
plt.plot(x, y)
plt.show()
但如果我定义函数绘图不起作用:
rr = np.arange(-5, 15, 2)
def y(o):
return np.sin(o / 2.) * np.exp(o / 4.) + 6. * np.exp(-o / 4.)
def h(b):
return int(y(b))
plt.plot(rr, h)
plt.show()
为什么会发生这种情况,以及如何更改代码来绘制函数?
发布于 2016-04-22 07:35:44
试着这样做:
import numpy as np
import matplotlib.pyplot as plt
rr = np.arange(-5, 15, 2)
def y(o):
return np.sin(o / 2.) * np.exp(o / 4.) + 6. * np.exp(-o / 4.)
plt.plot(rr, y(rr).astype(np.int))
plt.show()
发布于 2016-04-22 07:46:58
Hun的回答是正确的。
但是,如果您对使用两个函数定义非常感兴趣,那么可以尝试这样做:
def y(o):
return np.sin(o / 2.) * np.exp(o / 4.) + 6. * np.exp(-o / 4.)
def h(b):
l = []
for i in b:
l.append(int(y(i)))
return l
rr = np.arange(-5, 15, 2)
plt.plot(rr, h(rr))
plt.show()
为了回答为什么你的代码不能工作,当你调用函数'h‘时,你没有传递任何参数,因此这将返回函数定义或函数的内存位置指针。即使您将rr传递给h,h也不会被处理以将其转换为迭代器。
https://stackoverflow.com/questions/36787213
复制