Hi Guys, I was wondering how one would write a C program that calculates the value of a cosine function without using any library functions from <math.h>

I need the outputs to turn out like this

Case 1: cos(-1.000) = 0.540302303792
Case 2: cos(1.000) = 0.540302303792
Case 3: cos(1.500) = -0.125000000000
Case 4: cos(2.000) = -0.422222222222
Case 5: cos(2.000) = 1.000000000000

What came to my mind was that you can try interpolating a couple of points along the radians-axis like x = {(-3*pi), (-2*pi), -pi, 0, pi, (2*pi), (3*pi)} and the known cosine values; y = { 0, -1, 0, 1, 0, -1, 0 } . Now I'm using 7 points, but the more points you utilize the more precise your cosine curve will be when close to origo. This curve can be calculated beforehand (maybe look for the polynom ( cosPoly(x) ) for the curve).

Next step would be to take your angle ( A ) that you wish to calculate the cosine of, and do a unitCircleA = A mod PI .

Next, you just run cosOfA = cosPoly(unitCircleA) There you go! I can't recall the exact way to find the interpolation polynom atm, but I will return to you if it pops up. If accuracy is important, just try to increase the number of points ( n ) that are used in your interpolation. Interpolation of n points will give you a polynom of degree n-1 if done right. Also make sure that decimals are preserved all the way through, and that your approximation of PI is detailed enough.

Hope this helps!
Emil Olofsson

Edited 5 Years Ago by emilo35: Added some more code tags

This article has been dead for over six months. Start a new discussion instead.