

How does C compute sin() and other math functions? - aaronchall
http://stackoverflow.com/q/2284860/541136

======
EliRivers
There's nothing like hitting the source and seeing how someone has actually
done it in a library in common use; let's look at one C library implementation
in particular. I chose uLibC (
[http://git.uclibc.org/uClibc/tree/](http://git.uclibc.org/uClibc/tree/) )

Here's the sin function:

[http://git.uclibc.org/uClibc/tree/libm/s_sin.c](http://git.uclibc.org/uClibc/tree/libm/s_sin.c)

which looks like it handles a few special cases, and then carries out some
argument reduction to map the input to the range [-pi/4,pi/4], (splitting the
argument into two parts, a big part and a tail) before calling

[http://git.uclibc.org/uClibc/tree/libm/k_sin.c](http://git.uclibc.org/uClibc/tree/libm/k_sin.c)

which then operates on those two parts.

If there is no tail, an approximate answer is generated using a polynomial of
degree 13.

If there is a tail, you get a small corrective addition based on the principal
that _sin(x+y) = sin(x) + sin '(x')_y _

------
drallison
A C program computes sine by linking to a program, sin(), that computes it.
Usually the program works by examining the argument provided and using various
equivalence formulas to reduce the range to an interval for which there is a
good Tchebysheff polynomial or Pade rational approximation to sine. All this
is done keeping an eye on the representation and the potential for rounding
errors. Some of the computation may be done with integers, some the mantissa
and exponent independently, and so forth. A good knowledge of machine
arithmetic, arithmetic error propagation, and machine performance is needed to
make a universally acceptable sine function for C.

