Search code examples
pythonnumpymatplotlibpiecewise

Periodic piecewise sin-cos function


I need to get plot like this: enter image description here

So I found quite similar question and have tried to adapt solution for myself:

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()

But the result I got is: enter image description here

What am I doing wrong?

EDIT I decided to change a code a little bit, so the result could look like that: enter image description here

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()

Solution

  • I'm not sure your piecewise function is correct. I went on Desmos online graphing calculator and created a plot that matches what you're going for: Desmos graphing calculator image of piecewise function

    Then I used those formulas in the numpy.piecewise function:

    import numpy as np
    import matplotlib.pyplot as plt
    
    def Q(t):
        return np.piecewise(t, [np.sin(t/2)>0, np.sin(t/2)<=0], [lambda x:np.sin(3*x), lambda x:np.sin(x)*10])
    
    t = np.linspace(0, 18, 150)
    plt.plot(t, Q(t))
    plt.show()
    

    Matplotlib graph of piecewise function

    That seems to match your intended plot.