Saturday 20 July 2013

28. Write a C++ program to compute the Sine series.






SIne series:





\begin{align}
\sin x & = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \cdots \\[8pt]
& = \sum_{n=0}^\infty \frac{(-1)^n}{(2n+1)!}x^{2n+1} \\[8pt]
\end{align}


#include<iostream.h>
#define PI 3.1415926
void sin(float f,int n);
long fact(int n)
{
   long f=1;
   for(int i=1;i<=n;++i)
   f =f*i;
   return f;
}

double power(float b,int p)
{
    double k=1;
    for(int i=1;i<=p;++i)
    k=k*b;
    return k;
}

long power(int b,int p)
{
    long k=1;
    for(int i=1;i<=p;++i)
    k=k*b;
    return k;
}

int main()
{
        float x;
        int m ;
        cout<<"\n enter x value ";
        cin>>x;
        cout<<"\n enter n value ";
        cin>>m;
        while(m<0)
        {
             cout<<"\n enter n value ";
             cin>>m;
        }
        x=x*(PI/180);
        sin(x,m);
        return 0;
}

void sin(float x,int num)
{
int n,m;
long a,c;
double b,Result=0;
for(n=0;n<=num;++n)
{  
        a= power(-1,n) ;           //a =(-1)^n
        m=(2*n)+1;                   
        b=power(x,m);             //b=x^((2*n)+1)
        c=fact(m);                    //c=((2*n)+1)!
        Result=Result+((a*b)/c);
}
cout<<"sin value for "<<x<<" is : "<<Result;
}

No comments:

Post a Comment