使用 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
condlist 中使用小于/大于语句,这不是问题,但使用 Q_true
确定它是真还是假要容易得多。
情节应如下所示:
有什么想法吗?
谢谢!
I'm trying to generate a piecewise periodic plot using Numpy and matplotlib, like this:
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))
The problem is that Q_true
is receiving the entire t
array instead of individual points. This isn't an issue if I just use less than/greater than statements in the numpy.piecewise
condlist, but it's much easier to determine whether it's true or false using Q_true
.
The plot should look something like this:
Any ideas?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下版本的
Q_true
有效:请注意,您正在命名匿名函数 (
Q1 = lambda ...
)。在这种情况下,您应该只使用def
定义函数。The following version of
Q_true
works:Note that you are naming your anonymous functions (
Q1 = lambda ...
). In this case you should just define the function usingdef
.