17.01.2013 Views

musicdsp.org source code archive - WSInf

musicdsp.org source code archive - WSInf

musicdsp.org source code archive - WSInf

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Fast sine and cosine calculation (click this to go back to the index)<br />

Type : waveform generation<br />

References : Lot's or references... Check Julius O. SMith mainly<br />

Code :<br />

init:<br />

float a = 2.f*(float)sin(Pi*frequency/samplerate);<br />

float s[2];<br />

s[0] = 0.5f;<br />

s[1] = 0.f;<br />

loop:<br />

s[0] = s[0] - a*s[1];<br />

s[1] = s[1] + a*s[0];<br />

output_sine = s[0];<br />

output_cosine = s[1]<br />

Comments<br />

from : nigel<br />

comment : This is the Chamberlin state variable filter specialized for infinite Q oscillation. A few things to note:<br />

Like the state variable filter, the upper frequency limit for stability is around one-sixth the sample rate.<br />

The waveform symmetry is very pure at low frequencies, but gets skewed as you get near the upper limit.<br />

For low frequencies, sin(n) is very close to n, so the calculation for "a" can be reduced to a = 2*Pi*frequency/samplerate.<br />

You shouldn't need to resync the oscillator--for fixed point and IEEE floating point, errors cancel exactly, so the osciallator runs forever without drifting<br />

in amplitude or frequency.<br />

from : DFL<br />

comment : Yeah, this is a cool trick! :)<br />

FYI you can set s[0] to whatever amplitude of sinewave you desire. With 0.5, you will get +/- 0.5<br />

from : bigtick@pastnotecut.<strong>org</strong><br />

comment : After a while it may drift, so you should resync it as follows:<br />

const float tmp=1.5f-0.5f*(s[1]*s[1]+s[0]*s[0]);<br />

s[0]*=tmp; s[1]*=tmp;<br />

This assumes you set s[0] to 1.0 initially.<br />

'Tick<br />

from : DFL<br />

comment : Just to expalin the above "resync" equation<br />

(3-x)/2 is an approximation of 1/sqrt(x)<br />

So the above is actually renormalizing the complex magnitude.<br />

[ sin^2 (x) + cos^2(x) = 1 ]<br />

from : antiprosynthesis@hotmail.com<br />

comment : I made a nice little console 'game' using your cordic sinewave approximation. Download it at<br />

http://users.pandora.be/antipro/Other/Ascillator.zip (includes <strong>source</strong> <strong>code</strong>). Just for oldschool fun :).<br />

from : wink@op.pl<br />

comment : what da shit is this? i don't know why it is so interesting?<br />

from : hplus<br />

comment : Note that the peaks of the waveforms will actually be between samples, and the functions will be phase offset by one half sample's worth.<br />

If you need exact phase, you can compensate by interpolating using cubic hermite interpolation.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!