Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This project will introduce functions. A Taylor series expansion can approximate

ID: 3785600 • Letter: T

Question

This project will introduce functions. A Taylor series expansion can approximate various functions with its terms... the more terms, the closer to the real function value it is. The Taylor series expansion of sin(x) = sigma_n = 0^infinity (-1)^n/(2n + 1)! x^2n + 1, for all x, and the Taylor series of cos(x) = sigma_n = 0^infinity (-1)^n/(2n)! x^2n, for all x. Write two functions (using a new *.h and *.cpp file) that calculate sin(x) and cos(x), until the difference in successive sums is less than 10^-3. Write a program that prompts for x and uses your two functions to calculate these values. Print out the result. Test cases: sin(0.5) = 0.479425, cos(0.5) = 0.87758; sin(2) = 0.90929, cos(2) = -0.41614 Important! Use the factorial function given in class (from lecture) to do the denominators of the above equations.)

Explanation / Answer

#include <iostream>
using namespace std;

// pow function
double power (double x, int y)
{
   double p=1.0;
   for (int i=1; i<=y; i++)
       p=p*x;
   return p;
}

// factorial function
double fact(int x){
   double f=1.0;
   for (int i=1; i<=x; i++){
       f=f*i;
   }
   return f;
}

// Difference in successive terms for sine
double diffsine(double x,int n,int pos) {
   int pow = 2*n+1;
   double diff = (power (x,pow) / fact (pow));
   return diff;
}

// Difference in successive terms for cosine
double diffcosine(double x,int n,int pos) {
   int pow = 2*n;
   double diff = (power (x,pow) / fact (pow));
   return diff;
}

// Calculate Sine
double sine (double x) {
   double val1 = x,val2,diff;
   int n = 1,pos = -1;

   while(true) {
       diff = diffsine(x,n,pos);
       // cout << diff;
       val1 = val1 + pos*diff;
       if(diff<0.001)
           break;
       else {
          
           n++;
           pos = -1*pos;      
       }
   }
  
   return val1;
}

// Calculate Cosine
double cosine (double x) {
   double val1 = 1.0,val2,diff;
   int n = 1,pos = -1;

   while(true) {
       diff = diffcosine(x,n,pos);
       // cout << diff;
       val1 = val1 + pos*diff;

       if(diff<0.001)
           break;
       else {
           n++;
           pos = -1*pos;      
       }
   }
  
   return val1;
}

int main() {
   double x;
   cin >> x;
   cout << sine(x) << endl;
   cout << cosine(x) << endl;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote