Hacker News new | ask | show | jobs
by maep 1517 days ago
A commonly used way to create an discrete sine wave efficiently is to use an IIR oscilator. If it needs to be long running, use a real sin to correct for rounding errors every N samples. If you're using something like Q30 fixed point that correction doesn't have to happen that often.

https://dspguru.com/dsp/tricks/sine_tone_generator/

1 comments

The IIR oscillators quickly deterioritate, though. A more accurate way is to do something CORDIC-inspired: Start with a 2D point in [1,0]. Every iteration, you rotate it by (2pi f T) radians (where f is the frequency you want, and T is 1/48000 or whatever). This requires you to have precomputed sin and cos of those values for the rotation matrix, but that can be done once, up-front, as long as you don't need to change the frequency. If you do this for every sample, x will trace out your cos() and y will trace out your sin().

Accuracy errors are easy to account for in this scheme; just renormalize the vector so that the length is 1. It's cheaper and less code than doing a sin().

By the way, for linear interpolation (if you wish to keep the table), usually x + (y-x)*t is faster than x*(1-t) + y*t.