我正在绘制数十个函数作为子图,将纯函数存储为列表。我发现许多不同的函数被认为是相同的。下面是一个简化的示例,其中绘制了两个余弦函数。
#!/usr/bin/env python3
import math # cos
from matplotlib import pyplot as plt # Plotting.
scale =[0.01*x for x in list(range(200))]
list_fun =[lambda t: math.cos(2*math.pi*i*t) for i in [1,2]]
data_1 =list(map(list_fun[0], scale))
data_2 =list(map(list_fun[1], scale))
fig =plt.figure( figsize=(11,5) )
ax =fig.add_subplot(1, 2, 1) # left
ax.plot( scale, data_1, label="cos 2$\pi$t" )
ax.legend()
ax =fig.add_subplot(1, 2, 2) # right
ax.plot( scale, data_2, label="cos 4$\pi$t" )
ax.legend()
plt.show()
图中显示了两个$\cos (4\pi t)$
函数,但其中一个应该是$\cos (2\pi t)$
。我想由几个纯函数组成的列表在python中是无效的,是吗?如果是的话,是否有其他语法?我是Python新手,所以可能出现了一些明显的错误。
发布于 2017-05-30 17:42:05
您的list_fun
列表包含两个相同的函数,因为您是如何定义它的。这两个函数都返回math.cos(2*math.pi*i*t)
,其中i
有其最终值2。
您可以将i
复制到另一个变量以使其工作:
[lambda t, m=i: math.cos(2*math.pi*m*t) for i in [1,2]]
https://stackoverflow.com/questions/44268502
复制相似问题