taylor series to compute sin, cosine and tan

#include <iostream>
#include <cmath> // for pow() function


using namespace std;

// Recursion method : http://web.eecs.utk.edu/~cs102/lectures/recursion.html
float factorial(float number)
{
if (number == 0) return 1;
return number * factorial(number-1);
}

float DegToRad(float degree)
{
float radians = (degree / 360) * (2.0 * M_PI);
return radians;
}

/*
* Refer here for formulae : http://www.youtube.com/watch?v=dp2ovDuWhro
*/
void cSIN(float radian, int aprox)
{
float result = 0.0;

for(int x=1; x<aprox; x++)
{
float firstPart = pow (-1, (x+1)); //(-1)^n+1
float secondPart = pow(radian,((2*x)-1)); // x^2n-1
float thirdPart = factorial((2*x)-1); // (2n-1)!
result = result + firstPart*(secondPart/thirdPart);
}

cout<<"Result = "<<result<<endl;
}

int main()
{
cSIN(DegToRad(35),10);
return 0 ;
}







This is what i made so far to compute sine value. I need help to compute cosine value. Please help me
So I see that you implemented sin. You could use some improvements there as well. pow(-1,(x+1)) you can do instead:
 
firstPart=((x+1)%2==0)?1:-1;

The other comment is that you can compute the full term in the expansion at step x, as the term at step x-1 multiplied with -radian*radian/(1+2*x), kind of similar to the factorial implementation.

The formula for cos you can find it here http://www.wolframalpha.com/input/?i=taylor+series+cos+x
I dont understand. Can you help me to explain abit detailed?
Say for example for cos(x)=sum_k (-1)^k*x^(2k)/(2k)! The first term is for k=0, (-1)^0*x^0/0!=1.
If you look at the ratio between the last term of the sum at step k, and at step k-1, you see that it is -x^2/(2k)/(2k-1). I just noticed that I forgot a term in my previous comment.

You start with term_x=1, result=1, then you do your for loop from 1, and inside you say (with your notation)
term_x*=-radian*radian/(2*x)/(2*x-1)
result+=term_x

Similar, for sin(x), your k=0 term is x, your term_k=term_(k-1)*(-1)*x^2/(2*k)/(2*k+1)
i dont know how to implement the cosine taylor series..totally confused. Can u help with my code?
How does your code looks so far?
This is what translates to code what ats has shown
1
2
3
4
5
6
7
8
9
10
11
int cos(int x)
{
     int t = -x*x/2;
     int sum = 1 + t;
     for(int i=2;i<20;++i)
          {
              t*=-x*x/(2*i*(2*i-1));
              sum+=t;
          }
    return sum;
}
Last edited on
Topic archived. No new replies allowed.