Advertisement
makispaiktis

Calculating sin, cos with Taylor Series

Jan 3rd, 2020 (edited)
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdlib.h>
  3. #include <math.h>
  4.  
  5. using namespace std;
  6. // Factorial Function
  7. int factorial(int n){
  8.     if(n == 0){
  9.         return 1;
  10.     }
  11.     else{
  12.         return n * factorial(n-1);
  13.     }
  14. }
  15.  
  16. // Sinus Function
  17. double sinTaylor(double angle){
  18.     double rads = angle * M_PI / 180;
  19.     double sum = 0;
  20.     int sign = 1;
  21.     for(int i=1; i<=33; i+=2){
  22.         sum += sign * pow(rads, i) / factorial(i);
  23.         sign = -sign;
  24.     }
  25.     return sum;
  26. }
  27.  
  28. // Cosinus Function
  29. double cosTaylor(double angle){
  30.     double rads = angle * M_PI / 180;
  31.     double sum = 0;
  32.     int sign = 1;
  33.     for(int i=0; i<=32; i+=2){
  34.         sum += sign * pow(rads, i) / factorial(i);
  35.         sign = -sign;
  36.     }
  37.     return sum;
  38. }
  39.  
  40. int main()
  41. {
  42.     cout << "sin(0) = " << sin(0) << " = " << sinTaylor(0) << endl;
  43.     cout << "sin(15) = " << sin(15* M_PI / 180) << " = " << sinTaylor(15) << endl;
  44.     cout << "sin(30) = " << sin(30* M_PI / 180) << " = " << sinTaylor(30) << endl;
  45.     cout << "sin(45) = " << sin(45* M_PI / 180) << " = " << sinTaylor(45) << endl;
  46.     cout << "sin(60) = " << sin(60* M_PI / 180) << " = " << sinTaylor(60) << endl;
  47.     cout << "sin(75) = " << sin(75* M_PI / 180) << " = " << sinTaylor(75) << endl;
  48.     cout << "sin(90) = " << sin(90* M_PI / 180) << " = " << sinTaylor(90) << endl;
  49.     cout << endl;
  50.     cout << "cos(0) = " << cos(0) << " = " << cosTaylor(0) << endl;
  51.     cout << "cos(15) = " << cos(15* M_PI / 180) << " = " << cosTaylor(15) << endl;
  52.     cout << "cos(30) = " << cos(30* M_PI / 180) << " = " << cosTaylor(30) << endl;
  53.     cout << "cos(45) = " << cos(45* M_PI / 180) << " = " << cosTaylor(45) << endl;
  54.     cout << "cos(60) = " << cos(60* M_PI / 180) << " = " << cosTaylor(60) << endl;
  55.     cout << "cos(75) = " << cos(75* M_PI / 180) << " = " << cosTaylor(75) << endl;
  56.     cout << "cos(90) = " << cos(90* M_PI / 180) << " = " << cosTaylor(90) << endl;
  57.     cout << endl;
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement