How to plot sine wave in Python with sudden amplitude change?

后端 未结 3 1224
余生分开走
余生分开走 2021-01-27 20:32

Posted: 7/4/2020

I was wondering if anyone knows how to plot a sine wave with let\'s say amplitude of 0.1 as a start and then continuing on as usual. Until at one point,

3条回答
  •  佛祖请我去吃肉
    2021-01-27 20:52

    I have converted the code to period time:

    import matplotlib.pyplot as plt
    import math
    
    
    # ------------------------------------------------------------------------
    # uses the list amplitude_changes to get the amplitude for time t
    def get_amplitude(t):
        for amplitude_change in amplitude_changes:
            if t >= amplitude_change['t']:
                amplitude = amplitude_change['amplitude']
    
        return amplitude
    
    
    # --------------------------------------------------------------------------
    def y_func(time, period_time, amplitude):
        return amplitude * math.sin((time / period_time) * 2 * math.pi)
    
    # --------------------------------------------------------------------------
    
    
    t_values = []
    amplitude_values = []
    
    signal1Frequency = 50
    period_time = 1 / signal1Frequency
    sampling_frequency = 1500
    
    delta_t = 1 / sampling_frequency
    
    
    amplitude_changes = [
                            {'t': 0, 'amplitude': 1},
                            {'t': period_time * 0.9, 'amplitude': 1.5},
                            {'t': period_time * 0.95, 'amplitude': 1},
                            {'t': period_time * 1.2, 'amplitude': 0.8},
                            {'t': period_time * 1.25, 'amplitude': 1},
                        ]
    
    max_t = period_time * 3                     # plot 3 periods
    t = 0
    while t <= max_t:
        t_values.append(t)
        amplitude = get_amplitude(t)
        amplitude_values.append(y_func(t, period_time, amplitude))
        t += delta_t
    
    
    plt.plot(t_values, amplitude_values)
    plt.title(f'f = {signal1Frequency} Hz (T = {period_time}) - Sampling frequency = {sampling_frequency} Hz')
    plt.show()
    

    Result

提交回复
热议问题