Over the past few days, I have been playing around with the SNES SDK that compiles C code to SNES ROMs for running in emulators or on real hardware. The SDK supports floating point emulation, 16-bit integers, controller input, and a basic graphics system. There is no sound support in the SDK for the SPC of the SNES (yet). Libraries can be added to the SDK pretty easily by writing C code and compiling to assembly to be linked with other programs.

In playing with the SNES SDK, I noticed that in math.h, a lot of the ANSI C math functions were left out due to hardware limitations of the SNES. However, without much effort, I was able to create working functions for the six basic trig functions and a square root function.

In mathematics, sine and cosine can be approximated by Taylor polynomial expansions. This makes it easy to implement functions in C to compute the sine and cosine of a value to a certain degree of precision. The following is the Taylor expansion functions for sine and cosine:

I had to create helper functions for x^n and x! (x factorial) since those aren't built into the compiler. The function, mult(x, n), raises x to the power n. The function, fact(x), computes the factorial of x. There is a pow(x, n) function implemented in the SDK, but it doesn't produce as accurate of results as my mult(x, n) function. The result can be seen when running pow(2, 12) versus mult(2, 12). The pow function returns 4095 while mult returns 4096 (the correct result).

The other trig functions were built on the sin and cos functions. There is a Taylor expansion for tan(x), but I decided to go with sin(x)/cos(x) since I couldn't properly expand tan(x) for enough accuracy. Below is the rest of the trig functions:

I understand the practicality of computing trig values on the SNES might not be huge for everyday use. However, this was more of a "Can I do this?" type of exercise. Games like Starfox for the SNES may have used trig calculations on the Super FX co-processor, but I doubt many games needed cosine or sine functions calculated on the main CPU. Perhaps game demos with oscillating text used sine or cosine as a function of time.

The square root function is based on Newton's method. I found the code for this method here: http://www.codeproject.com/Articles/69941/Best-Square-Root-Method-Algorithm-Function-Precisi