优化时间线构建器功能

Optimization of a timeline builder function

我有一个频率为 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 之间循环以创建一个列表,其中是方块开始的时间。我很确定这不是最好的方法,我想知道如何改进它。

谢谢。

如果我的解释是正确的,那么您正在寻找从 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)]

为此使用标准库 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