So I'm just doing a little project that's meant to help me understand what some basic mathematical operations actually mean (square root, sine, etc). I'm trying to program my own calculator without using anything in math.h (the code below uses it, but that's because I wanted to work on this particular problem first, which cannot be done without exponents).
So basically what my code is doing is approximating sine using a Maclaurin polynomial. The function will take in a number and the degree of the polynomial to approximate sine, then spit out an approximate value. The value is meant to get more accurate as the degree of the polynomial increases. HOWEVER. I've found that at around degree 15, I start to get wacky results like -2. I know this has something to do with the rounding and ability of C++ to handle a certain amount of decimal places, but I'm wondering if somebody can point me toward a resource that would help to explain this to me more in-depth. My goal is to be able to approximate sine to *arbitrary* accuracy. i.e. I want to be able to make the degree of the approximating polynomial as high as I want without getting these wacky results. Any help appreciated![:)]()
So basically what my code is doing is approximating sine using a Maclaurin polynomial. The function will take in a number and the degree of the polynomial to approximate sine, then spit out an approximate value. The value is meant to get more accurate as the degree of the polynomial increases. HOWEVER. I've found that at around degree 15, I start to get wacky results like -2. I know this has something to do with the rounding and ability of C++ to handle a certain amount of decimal places, but I'm wondering if somebody can point me toward a resource that would help to explain this to me more in-depth. My goal is to be able to approximate sine to *arbitrary* accuracy. i.e. I want to be able to make the degree of the approximating polynomial as high as I want without getting these wacky results. Any help appreciated
int factorial(int n) //function takes an integer and returns its factorial.
{
int result=1;
for(int i = 1; i<(n+1) ; i++)
{
result=result*i;
}
return(result);
}
float sin(float n, int degree) //function approximates sin(n) through the use of a Maclaurin polynomial of a user-defined degree
{
int sign=1;
float x=n;
float addx;
for (int i=1; i<degree ; i++)
{
sign=pow(-1,i);
addx=pow(n,(2*i +1))/(factorial(2*i +1));
x=x+sign*addx;
}
return(x);
}