October 1, 2008
stumbling in code
So while playing with some code to model a resonating spring (F=-k*pos), I discovered that
the model I was using produced a very good sine wave approximation. This isn't
normally something terribly interesting, as you can approximate sine/cosines
very easily, but it was actually quite low complexity -- an iterative
approximation with only 2 multiplies and 3 adds per sample. It can also
generate the cos() (well, a 90 degree shifted signal) for each point for just one additional multiply.
The error is pretty low for the first few cycles, though after a bit it does
drift in relation to the correct wave. I'm not going to spend too much more
time on this, but if anybody wants to see if there's some way to correct it,
go for it (it may just be rounding error, though, of course).
Here is the code:
Ta-da! If anybody wants to go and do some fancy pants math to show why this works, too, I'd love to hear it... :)