Triangle wave shaped array in Python

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

    You can use an iterator generator along with the numpy fromiter method.

    import numpy
    
    def trigen(n, amp):
        y = 0
        x = 0
        s = amp / (n/4)
        while x < n:
            yield y
            y += s
            if abs(y) > amp:
                s *= -1
            x += 1
    
    a = numpy.fromiter(trigen(100, 0.5), "d")
    

    Now you have an array with the square wave.

提交回复
热议问题