Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _USE_MATH_DEFINES
- #include <iostream>
- #include <math.h>
- double CalcFactorial(unsigned int n)
- {
- if (n <= 1) return 1;
- double result = 1;
- for (size_t i = 1; i < n; i++)
- {
- result += result * i;
- }
- return result;
- }
- // - - - - - - - - - - - - - - - - - -
- // Calc series sum from [start n] to [end n]
- double CalcSeries(int startN, int endN, double (*func)(double))
- {
- double result = 0.0;
- for (size_t n = startN; n <= endN; n++)
- {
- result += func(n);
- }
- return result;
- }
- // Calc functional series sum from [start n] to [end n]
- double CalcSeries(int startN, int endN, double x, double (*func)(double, double))
- {
- double result = 0.0;
- for (size_t n = startN; n <= endN; n++)
- {
- result += func(n, x);
- }
- return result;
- }
- // - - - - - - - - - - - - - - - - - -
- double CalcSin(double x, int calcSteps)
- {
- // Normalize argument to the range [-2pi, 2pi]
- {
- if (x > 2 * M_PI || x < 2 * M_PI)
- {
- x = fmod(x, 2 * M_PI);
- }
- }
- return CalcSeries(0, calcSteps, x,
- [] (double n, double x) {
- return pow(-1, n) * pow(x, 2 * n + 1) / CalcFactorial(2 * n + 1);
- }
- );
- }
- double CalcCos(double x, int calcSteps)
- {
- return - CalcSin(x - M_PI_2, calcSteps);
- }
- // - - - - - - - - - - - - - - - - - -
- void test(double t)
- {
- int calcSteps = 10;
- printf_s("sin(%.2f):\n", t);
- printf_s("my_calc = %8.5f\n", CalcSin(t, 10));
- printf_s("std_calc = %8.5f\n\n", sin(t));
- }
- // - - - - - - - - - - - - - - - - - -
- int main()
- {
- double input;
- while (true)
- {
- std::cin >> input;
- test(input);
- }
- return (0);
- }
- /*
- Output:
- -121
- sin(-121.00):
- my_calc = -0.99882
- std_calc = -0.99882
- 2
- sin(2.00):
- my_calc = 0.90930
- std_calc = 0.90930
- 6
- sin(6.00):
- my_calc = -0.27939
- std_calc = -0.27942
- 8
- sin(8.00):
- my_calc = 0.98936
- std_calc = 0.98936
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement