Nintendo DS: Sine approximation using fixed point math

When I was writing the Nintendo DS 4k intro, I obviously needed sin and cos functions to set up rotation matrices. Since using the C standard library for this task would have exceeded the 4kb limit easily, I was looking for an alternative that does not use much memory.

I was searching for an approximation method using taylor series and google made me visit these sites:

The only task left for me was porting it from float to fixed point. I didn’t really care about precision or performance much, something that reminds to a sine-wave and isn’t horribly slow would suffice.

Suprisingly, the fixed-point sin approximation is quite precise. At least more precise than I though it would be. Here is a screenshot of the original sinf routine (green) and the approximated one (red) using the source code below:

Nintendo DS sine approximation

Well, there is an issue with my code. When the incoming radians parameter is getting bigger (1000 and above), precision is getting worse, but this is an issue that can be fixed if you’re up to.

The routine from polygon labs can’t really handle radians greater than 2*PI, which I tried to fix by normalizing it to an angle between -1..+1 and then just use a bit-AND to discard all numbers outside this range.

I wanted to keep the radians format for the incoming parameter, because it’s how the standard sinf routine works. Using another range, like 0..4096 to represent a full rotation would probably solve that precision problem with large radians because this would remove the need for the first two code lines, but I want 2*PI.

Here is the source code, to be compiled with libnds and devkitARM:

Let me know when you fixed the precision problem with large radian values 🙂

Edit: Jasper “cearn” Vijn apparently likes challenges or in his own words:

So here I am, looking forward to a nice quiet weekend; hang back, watch some telly and maybe read a bit – but NNnnneeeEEEEEUUUuuuuuuuu!! Someone had to write an interesting article about sine approximation. With a challenge at the end. And using an inefficient kind of approximation. And so now, instead of just relaxing, I have to spend my entire weekend and most of the week figuring out a better way of doing it. I hate it when this happens >_<.

Don’t miss to read his article Another fast fixed-point sine approximation.

For completeness, I post a fixed version of the method above. I highly encourage you to visit Jasper’s site and get one of his better sine approximation functions though.