So I decided I wanted to make a C program to converge to the value the function cosine(x) give for any given x. Having used the Maclaurin Series in the past for Calculus, I knew this should be an easy implementation.
Using Maclaurin series in this case, you do a summation from 0 to infinity. Well obviously you can't make it go to infinity, so I want to iterate as many times for accuracy as possible.
Well it seems that if I set my iterations past 10, my numbers go real wacky. I need to set it higher because if I run 0 through cosine(0), I naturally get 1. But if I run 2pi through, I get 0.996515. Can anyone see if I am overflowing anything or doing something wrong?
Also, I know I am no perfect programmer, but if you will critique, please also help me with my original problem, because this is no final draft.
Code:
#include <stdio.h>
float power (float base, float exponent);
unsigned long long factorial (int input);
float cosine (float input);
float pi = 3.141592;
int main (void)
{
printf("%f\n", cosine(2*pi));
return 0;
}
float power (float base, float exponent)
{
int i;
float product = 1.0;
for (i = 0; i < exponent; i++)
product *= base;
return product;
}
unsigned long long factorial (int input)
{
int i;
unsigned long long product = 1;
for (i = 0; i < input; i++)
product *= input - i;
return product;
}
float cosine (float input)
{
unsigned int i;
float sum = 0.0;
for (i = 0; i < 10; i++)
sum += power(-1, i) * power(input, 2*i) / factorial(2*i);
return sum;
}