user1610950
user1610950

Reputation: 1917

Generating a smooth sinusoidal wave

I am creating a program to generate a sinusoidal wave over a long period of time.

Currently I am doing it like this, every update. with these starting values for time 0.0f;

    time += 0.025f;
    if(time > 1.0f)
    {
        time -= 2.0f;
    }

The problem with this approach is that as you can see I have some value that if time goes beyond that my calculations start to break. So I need to reset it back to something less than that value.

Doing it this way there's obvious jumps in my wave once it's passed that threshold.

What's the method to make a smooth sine wave without this limitation?

Upvotes: 0

Views: 1069

Answers (1)

Lutz Lehmann
Lutz Lehmann

Reputation: 26040

You can use the trigonometric theorems to get an iteration for the sequence of sine values.

sin(A+B) + sin(A-B) = 2*sin(A)*cos(B)

Thus if you want to generate the sequence of values sin(w*k*dt) then you only have to compute

s[0] = 0, s[1] = sin(w*dt), cc = 2*cos(w*dt)

and then iterate

s[k+1] = cc*s[k] - s[k-1]

This linear recursion has eigenvalues on the unit circle and thus accumulates floating point errors, which may lead to phase shift and changes in amplitude over very long time spans. However, locally it will always look like a sine wave.

The second effect can be avoided by iterating the cosine sequence c[k]=cos(w*k*dt) at the same time,

s[k+1] = c[1]*s[k] + s[1]*c[k]
c[k+1] = c[1]*c[k] - s[1]*s[k]

and periodically rescaling the pair c[k],s[k] to have euclidean length 1.

Upvotes: 3

Related Questions