Efficient calculation of cosine in python

左心房为你撑大大i 提交于 2019-12-12 08:55:04

问题


I generate some time-series out of a theoretical power spectral density.

Basically, my function in time-space is given by X(t) = SUM_n sqrt(a_n) + cos(w_n t + phi_n), where a_n is the value of the PSD at a given w_n and phi is some random phase. To get a realistic timeseries, i have to sum up 2^25 modes, and my t of course is sized 2^25 as well.

If i do that with python, this will take some weeks...
Is there any way to speed this up? Like some vector calculation?

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

where dataCOS is sqrt a_n, w = w and random.uniform represents the random phase shift phi


回答1:


You can use the outer functions to calculate the angles and then sum along one axis to obtain your signal in a vectorized way:

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)

This is faster because when you use a Python for loop the interpreter will loop at a slower speed compared to a C loop. In this case, using numpy outer operations allow you to compute the multiplications and sums at the C loop speed.



来源:https://stackoverflow.com/questions/19364168/efficient-calculation-of-cosine-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!