2012-09-08 179 views
10

生成一个由100个数组构成的数组的最有效方法是什么?最大/最小幅度为0.5时,形成下面三角波的形状?Python中的三角波形阵列

记三角波形:

enter image description here

+0

您是否需要安排数据结构或绘制图形表示呢? –

+0

只需要制作一个采用该形状的100个数据条目的数组。不需要图形表示! – 8765674

+0

维基百科有三种不同的公式可以用来计算三角波:http://en.wikipedia.org/wiki/Triangle_wave#Definitions可能有更快的方法,但实现这些方程之一应该是一个不错的起点。 –

回答

8

使用发电机:

def triangle(length, amplitude): 
    section = length // 4 
    for direction in (1, -1): 
     for i in range(section): 
      yield i * (amplitude/section) * direction 
     for i in range(section): 
      yield (amplitude - (i * (amplitude/section))) * direction 

这会工作的优良被4整除的长度,你可能会错过了为其他3个值长度。

>>> list(triangle(100, 0.5)) 
[0.0, 0.02, 0.04, 0.06, 0.08, 0.1, 0.12, 0.14, 0.16, 0.18, 0.2, 0.22, 0.24, 0.26, 0.28, 0.3, 0.32, 0.34, 0.36, 0.38, 0.4, 0.42, 0.44, 0.46, 0.48, 0.5, 0.48, 0.46, 0.44, 0.42, 0.4, 0.38, 0.36, 0.33999999999999997, 0.32, 0.3, 0.28, 0.26, 0.24, 0.21999999999999997, 0.2, 0.18, 0.15999999999999998, 0.14, 0.12, 0.09999999999999998, 0.08000000000000002, 0.06, 0.03999999999999998, 0.020000000000000018, -0.0, -0.02, -0.04, -0.06, -0.08, -0.1, -0.12, -0.14, -0.16, -0.18, -0.2, -0.22, -0.24, -0.26, -0.28, -0.3, -0.32, -0.34, -0.36, -0.38, -0.4, -0.42, -0.44, -0.46, -0.48, -0.5, -0.48, -0.46, -0.44, -0.42, -0.4, -0.38, -0.36, -0.33999999999999997, -0.32, -0.3, -0.28, -0.26, -0.24, -0.21999999999999997, -0.2, -0.18, -0.15999999999999998, -0.14, -0.12, -0.09999999999999998, -0.08000000000000002, -0.06, -0.03999999999999998, -0.020000000000000018] 
+0

比我的尝试更有效。谢谢! – 8765674

+1

将'range'改为'xrange'(如果它是python <3) – zenpoy

1

您可以使用迭代器生成器以及numpy fromiter方法。

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

现在你有一个方波阵列。

4

要使用numpy的:

def triangle2(length, amplitude): 
    section = length // 4 
    x = np.linspace(0, amplitude, section+1) 
    mx = -x 
    return np.r_[x, x[-2::-1], mx[1:], mx[-2:0:-1]] 
2

三角是锯齿的绝对值。

from scipy import signal 
time=np.arange(0,1,0.001) 
freq=3 
tri=np.abs(signal.sawtooth(2 * np.pi * freq * time)) 
4

生成三角波的最简单方法是使用signal.sawtooth。注意signal.sawtooth(phi,width)接受两个参数。第一个参数是阶段,下一个参数指定对称性。宽度= 1给出右侧锯齿,宽度= 0给出左侧锯齿,宽度= 0.5给出对称三角形。请享用!

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)