Triangle wave shaped array in Python

前端 未结 6 1288
生来不讨喜
生来不讨喜 2021-02-08 04:22

What is the most efficient way to produce an array of 100 numbers that form the shape of the triangle wave below, with a max/min amplitude of 0.5?

Triangle waveform in m

6条回答
  •  忘掉有多难
    2021-02-08 04:31

    Here is a home-made python function for triangular signals

    import matplotlib.pyplot as plt
    import numpy as np
    phase=-10
    length=30 # should be positive
    amplitude=10
    x=np.arange(0,100,0.1)
    def triang(x,phase,length,amplitude):
        alpha=(amplitude)/(length/2)
        return -amplitude/2+amplitude*((x-phase)%length==length/2) \
                +alpha*((x-phase)%(length/2))*((x-phase)%length<=length/2) \
                +(amplitude-alpha*((x-phase)%(length/2)))*((x-phase)%length>length/2)
    
    tr=triang(x,phase,length,amplitude)
    plt.plot(tr)
    

提交回复
热议问题