使用numpy.piecewise生成分段周期图时的条件检查
我正在尝试使用Numpy和matplotlib生成一个分段周期性的图像,像这样:
import numpy as np
import matplotlib.pyplot as plt
Q1 = lambda t, f, Q_max: Q_max * np.sin(2 * np.pi *f * t)
Q2 = lambda t, f, Q_max: 0
def Q_true(t, f, stat):
while(t >= 1/f):
t -= 1/f
while(t < 0):
t += 1/f
return ((t <= 1/(2*f)) == stat)
Q = lambda t, f, Q_max: np.piecewise(t, [Q_true(t, f, True) , Q_true(t,f, False)], [Q1, Q2], f, Q_max)
Q_max = 225 # mL/sec
f = 1.25 # Hz
t = np.linspace(0,4,101) # secs
plt.plot(t, Q(t, f, Q_max))
问题是,Q_true
接收的是整个t
数组,而不是单独的点。如果我在numpy.piecewise
的条件列表中只使用大于或小于的判断,这就不是问题了,但使用Q_true
来判断真假要简单得多。
这个图应该看起来像这样:
有什么想法吗?
谢谢!
1 个回答
3
下面这个版本的 Q_true
是可以工作的:
def Q_true(t, f, stat):
period = 1/f
return (t % period < period/2) == stat
注意,你在给你的匿名函数命名(比如 Q1 = lambda ...
)。在这种情况下,你应该直接用 def
来定义这个函数。