Advertisement
QwarkDev

calculate sin using math (functional series) | C++

Jan 31st, 2021
1,083
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1.  
  2. #define _USE_MATH_DEFINES
  3.  
  4. #include <iostream>
  5. #include <math.h>
  6.  
  7. double CalcFactorial(unsigned int n)
  8. {
  9.     if (n <= 1) return 1;
  10.  
  11.     double result = 1;
  12.  
  13.     for (size_t i = 1; i < n; i++)
  14.     {
  15.         result += result * i;
  16.     }
  17.  
  18.     return result;
  19. }
  20.  
  21. // - - - - - - - - - - - - - - - - - -
  22.  
  23. // Calc series sum from [start n] to [end n]
  24. double CalcSeries(int startN, int endN, double (*func)(double))
  25. {
  26.     double result = 0.0;
  27.  
  28.     for (size_t n = startN; n <= endN; n++)
  29.     {
  30.         result += func(n);
  31.     }
  32.  
  33.     return result;
  34. }
  35.  
  36. // Calc functional series sum from [start n] to [end n]
  37. double CalcSeries(int startN, int endN, double x, double (*func)(double, double))
  38. {
  39.     double result = 0.0;
  40.  
  41.     for (size_t n = startN; n <= endN; n++)
  42.     {
  43.         result += func(n, x);
  44.     }
  45.  
  46.     return result;
  47. }
  48.  
  49. // - - - - - - - - - - - - - - - - - -
  50.  
  51. double CalcSin(double x, int calcSteps)
  52. {
  53.     // Normalize argument to the range [-2pi, 2pi]
  54.     {
  55.         if (x > 2 * M_PI || x < 2 * M_PI)
  56.         {
  57.             x = fmod(x, 2 * M_PI);
  58.         }
  59.     }
  60.  
  61.     return CalcSeries(0, calcSteps, x,
  62.         [] (double n, double x) {
  63.             return pow(-1, n) * pow(x, 2 * n + 1) / CalcFactorial(2 * n + 1);
  64.         }
  65.     );
  66. }
  67.  
  68. double CalcCos(double x, int calcSteps)
  69. {
  70.     return - CalcSin(x - M_PI_2, calcSteps);
  71. }
  72.  
  73. // - - - - - - - - - - - - - - - - - -
  74.  
  75. void test(double t)
  76. {
  77.     int calcSteps = 10;
  78.  
  79.     printf_s("sin(%.2f):\n", t);
  80.     printf_s("my_calc  = %8.5f\n", CalcSin(t, 10));
  81.     printf_s("std_calc = %8.5f\n\n", sin(t));
  82. }
  83.  
  84. // - - - - - - - - - - - - - - - - - -
  85.  
  86. int main()
  87. {
  88.     double input;
  89.  
  90.     while (true)
  91.     {
  92.         std::cin >> input;
  93.  
  94.         test(input);
  95.     }
  96.  
  97.     return (0);
  98. }
  99.  
  100. /*
  101. Output:
  102.  
  103. -121
  104. sin(-121.00):
  105. my_calc  = -0.99882
  106. std_calc = -0.99882
  107.  
  108. 2
  109. sin(2.00):
  110. my_calc  =  0.90930
  111. std_calc =  0.90930
  112.  
  113. 6
  114. sin(6.00):
  115. my_calc  = -0.27939
  116. std_calc = -0.27942
  117.  
  118. 8
  119. sin(8.00):
  120. my_calc  =  0.98936
  121. std_calc =  0.98936
  122. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement