You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

分段周期正余弦函数绘图异常及代码优化求助

分段周期正余弦函数绘图问题

我需要绘制分段周期交替的正余弦函数图像(目标图像特征:每个周期内前半段和后半段分别采用不同的正余弦组合波形)。

参考Stack Overflow上的相似问题,我编写了以下代码:

def complex_abstract_generator():
    def Q1(t, f):
        return (np.sin(2 * np.pi *f*t) + np.cos(2 * np.pi *f*t))
    def Q2(t, f):
        return 2*np.cos(2 * np.pi *f*t)

    def Q_true(t, f, stat):
        period = 1 / f
        return (t % period < period / 2) == stat

    def Q(t, f):
        return np.piecewise(t, [Q_true(t, f, True), Q_true(t, f, False)], [Q1, Q2], f)

    t = np.linspace(0, 10, 150)
    f = 1/(1*np.pi)
    plt.plot(t, Q(t, f))
    plt.show()

但运行后得到的图像不符合预期(错误图像特征:波形未按半周期分段切换,呈现连续的异常波动)。请问代码哪里出错了?


编辑:我调整了代码,现在期望绘制的目标图像特征为:三段式分段周期波形,分别对应不同振幅的正弦函数和高频正弦函数。调整后的代码如下:

def complex_abstract_generator(time, delta):
    def Q_true(t):
        return ((np.sin(2 * t + np.pi)) >= 0) & (np.sin(2*t) < 0)
    def Q(t):
        return np.piecewise(t, [(np.sin(2*t) >= 0), Q_true(t), (np.sin(t) < 0)],
                            [ lambda x: np.sin(2*x) * 10, lambda x: np.sin(2*x ) * 5, lambda x: np.sin(8 * x + np.pi)])

    t = np.linspace(0, 18, 200)
    plt.plot(t, Q(t))
    plt.show()

但依然没有得到预期效果,问题出在哪里?


内容的提问来源于stack exchange,提问作者Noerigarnhy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 00:55:04