Triangle wave shaped array in Python

前端 未结 6 1259
生来不讨喜
生来不讨喜 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:50

    The simplest way to generate a triangle wave is by using signal.sawtooth. Notice that signal.sawtooth(phi, width) accepts two arguments. The first argument is the phase, the next argument specifies the symmetry. width = 1 gives a right-sided sawtooth, width = 0 gives a left-sided sawtooth and width = 0.5 gives a symmetric triangle. Enjoy!

    from scipy import signal
    import numpy as np
    import matplotlib.pyplot as plt
    t = np.linspace(0, 1, 500)
    triangle = signal.sawtooth(2 * np.pi * 5 * t, 0.5)
    plt.plot(t, triangle)
    

提交回复
热议问题