I have to calculate the following:
float2 y = CONSTANT;
for (int i = 0; i < totalN; i++)
h[i] = cos(y*i);
totalN is a large number, so I would like to make this in a more efficient way. Is there any way to improve this? I suspect there is, because, after all, we know what’s the result of cos(n), for n=1..N, so maybe there’s some theorem that allows me to compute this in a faster way. I would really appreciate any hint.
Thanks in advance,
Federico
Using one of the most beautiful formulas of mathematics, Euler’s formula
exp(i*x) = cos(x) + i*sin(x),substituting
x := n * phi:cos(n*phi) = Re( exp(i*n*phi) )sin(n*phi) = Im( exp(i*n*phi) )exp(i*n*phi) = exp(i*phi) ^ nPower
^nisnrepeated multiplications.Therefore you can calculate
cos(n*phi)and simultaneouslysin(n*phi)by repeated complex multiplication byexp(i*phi)starting with(1+i*0).Code examples:
Python:
or C: