morty
morty

Reputation: 154

How to write Maclaurin Expansion of sin(x) using recursion in C++

I want to write a recursive function to calculate the Maclaurin Expansion of sin(x). It goes like this: sin(x)=x-(xˆ3/3!)+(xˆ5/5!)-(xˆ7/7!)+(xˆ9/9!)...

    double sin(int n, double x){ // n is the exponent, x is the value
    if(n == 1)
        return x;
    if() // WHAT TO SET THE CONDITION TO ?
        return sin(n-2,x) - (pow(x,n-2)/fact(n-2)); // fact is a function I have to calculate the factorial
    else
        return sin(n-2,x) + (pow(x,n-2)/fact(n-2));
    }

I am having problems with setting the if condition, so that one time I add values, the next time I subtract values.

Upvotes: 0

Views: 1980

Answers (1)

morty
morty

Reputation: 154

double sin(int n, double x){ // n is the exponent, x is the value
  if(n == 1)
     return x;
  if( ((n-1)/2) % 2 != 0)
     return  sin(n-2,x) - (pow(x,n)/fact(n)) ;
  else
     return  sin(n-2,x) + (pow(x,n)/fact(n)) ;
}

Upvotes: 1

Related Questions