我有一个频率为f的平方信号,我对广场开始的时间感兴趣。
def time_builder(f, t0=0, tf=300):
"""
Function building the time line in ms between t0 and tf with a frequency f.
f: Hz
t0 and tf: ms
"""
time = [t0] # /!\ time in ms
i = 1
while time[len(time)-1] < tf:
if t0 + (i/f)*1000 < tf:
time.append(t0 + (i/f)*1000)
else:
break
i += 1
return time
因此该函数在t0和tf之间循环以创建一个列表,其中是一个正方形开始的时间。我很确定这不是最好的方法,而且我想知道如何改进它。
感谢。
答案 0 :(得分:1)
如果我解释这是正确的,那么你正在寻找波浪的时间列表,从t0开始到tf结束。
def time_builder(f, t0=0, tf=300):
"""
Function building the time line in ms between t0 and tf with a frequency f.
f: Hz
t0 and tf: ms
"""
T = 1000 / f # period [ms]
n = int( (tf - t0) / T + 0.5 ) # n integer number of wavefronts, +0.5 added for rounding consistency
return [t0 + i*T for i in range(n)]
答案 1 :(得分:1)
使用标准库python可能不是最好的方法...特别是考虑到你以后可能想要做其他事情。
另一种方法是使用numpy
。这将允许您执行以下操作
from numpy import np
from scipy import signal
t = np.linspace(0, 1, 500, endpoint=False)
s = signal.square(2 * np.pi * 5 * t) # we create a square signal usign scipy
d = np.diff(s) # obtaining the differences, this tell when there is a step.
# In this particular case, 2 means step up -2 step down.
starts = t[np.where(d == 2)] # take the times array t filtered by which
# elements in the differences array d equal to 2
答案 2 :(得分:0)
从2个答案中找出更好的解决方案。
def time_builder(f, t0=0, tf=300):
return list(np.arange(t0, tf, 1/f*1000))
有时候考虑更简单的事情需要花费时间x&#39;)