gpt4 book ai didi

python - python中余弦的高效计算

转载 作者:太空狗 更新时间:2023-10-30 02:32:14 24 4
gpt4 key购买 nike

我根据理论功率谱密度生成了一些时间序列。

基本上,我的时空函数由 X(t) = SUM_n sqrt(a_n) + cos(w_n t + phi_n) 给出,其中 a_nPSD 在给定 w_nphi 处的值是某个随机相位。为了获得真实的时间序列,我必须总结 2^25 模式,我的 t 当然也是大小 2^25

如果我用 python 来做,这将需要几周的时间...
有什么办法可以加快速度吗?喜欢一些矢量计算?

t_full = np.linspace(0,1e-2,2**12, endpoint = False) 
signal = np.zeros_like(t_full)
for i in range(w.shape[0]):
signal += dataCOS[i] * np.cos(2*np.pi* t_full * w[i] + random.uniform(0,2*np.pi))

其中 dataCOS 是 sqrt a_n,w = w,random.uniform 表示随机相移 phi

最佳答案

您可以使用 outer 函数计算角度,然后沿一个轴求和以矢量化方式获得信号:

import numpy as np

t_full = np.linspace(0, 1e-2, 2**12, endpoint=False)
thetas = np.multiply.outer((2*np.pi*t_full), w)
thetas += 2*pi*np.random.random(thetas.shape)

signal = np.cos(thetas)
signal *= dataCOS

signal = signal.sum(-1)

这更快,因为当您使用 Python for 循环时,与 C 循环相比,解释器将以更慢的速度循环。在这种情况下,使用 numpy 外部运算允许您以 C 循环速度计算乘法和求和。

关于python - python中余弦的高效计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19364168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com