Page 1 of 1

sin() and arccos() implementations

Posted: Sun Jun 06, 2010 5:54 am
by accelleon
I've been searching for two hours now on how I can implement sin() and arccos() for my standard headers in my os. So far I don't understand how how computers calculate the sine of an angle with only the angle. I'm going into algebra 2 next year and I've even tried making the function myself, with no luck.

I'm asking if anyone can show me how a computer calculates the sine or arccosine of an angle with only the angle. I need this for my VGA driver's drawCircle function. So if anyone has their own implementation or can show me how to make one I would be grateful.

Re: sin() and arccos() implementations

Posted: Sun Jun 06, 2010 9:53 am
by Andyhhp
hehe - no easy question you ask there

To learn how to calculate sines and cosines from just angles, you need to understand calculus and taylor series. In the absence of knowing these, just trust me that the following equations are true:

sine(x) = x - x^3/3! + x^5/5! - x^7/7! ...
cosine(x) = 1 - x^2/2! + x^4/4! - x^6/6! ...

These are in fact infinite sequences so the only way to be exact is to calculate forever. However, the equations as shown above should be a good enough aproximation in the first cycle for what you need. (http://en.wikipedia.org/wiki/File:Taylorsine.svg)

There are some other subltaties:

x is the angle measured in radians. 360 degrees = 2PI radians
the functions are periodic outside the range +-PI therefore take x and modulo it with PI before attempting to caculate.

Furthermore, there is no way that this is even pretending to be an optimised approach. It will be slow but it will work. An example can be found http://www.xbdev.net/c_and_cpp/sin_cos_functions/index.php but i suggest you dont just copy it without understanding what is supposed to be going on - it uses a different method.

Finally, arccos is somewhat harder but defined as follows:

arccos(z) = PI/2 - (z + (1/2)z^3/3 + (3/8)z^5/5 + (15/24)z^7/7 ..... )

In this case, z is a number in the range -1 to 1 and arccos gives you back the answer in radians.

Does this help?

Re: sin() and arccos() implementations

Posted: Sun Jun 06, 2010 8:40 pm
by accelleon
Yes that helps, thanks. I understand the taylor series now, but not the other example you gave.
Anyway it shouldn't be too hard to implement the taylor series into my OS. If its too slow I'll just try to understand the other example you gave. Again thanks.

EDIT:
I got this code for sin(x):

Code: Select all

double sin(double a)
{
   double num = a * (pi()/180);//convert to radians
   double precision = 19;//number of expressions
    double value = 0;//init value
    for(int n = 0; n < precision; n++)//loop through expressions
        value += pow(-1.0, n) * pow(num, 2*n+1) / factorial(2*n + 1);
   return num - value;//return value
}


but for arccos im lost.