vadimk772336

Untitled

Oct 17th, 2019
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 13.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3. #include <vector>
  4. #include <Windows.h>
  5. #include <stdlib.h>
  6. #include <fstream>
  7. #include <string.h>
  8.  
  9. using namespace std;
  10.  
  11. const double PI = 3.1415926535897932384626433832795;
  12.  
  13. typedef double(*functiontype)(double x);
  14.  
  15. typedef struct Node
  16. {
  17.     double x, y;
  18. } Node;
  19.  
  20. typedef struct Interval
  21. {
  22.     double InitialNode, EndNode;
  23. } Interval;
  24.  
  25. int Factorial(int n)
  26. { // Факториал
  27.     int x = 1;
  28.     for (int i = 1; i <= n; i++)
  29.     {
  30.         x *= i;
  31.     }
  32.     return x;
  33. }
  34.  
  35. double Myfunk(double x)
  36. {
  37.     return (x*x);
  38. }
  39.  
  40. double exponenta(double x)
  41. { // Экспонента
  42.     return exp(x);
  43. }
  44.  
  45. void ValueUniformTable(functiontype* f, Node* Array, double Initial, double End, int Count)
  46. { // Создание равномерной таблицы значений
  47.     double step = abs(Initial - End) / (Count - 1);
  48.     Array[0].x = Initial;
  49.     Array[0].y = (*f)(Array[0].x);
  50.     //std::cout << Array[0].x << "      " << Array[0].y << endl;
  51.     for (int i = 1; i < Count; i++)
  52.     {
  53.         Array[i].x = Array[i - 1].x + step;
  54.         Array[i].y = (*f)(Array[i].x);
  55.         //std::cout << Array[i].x << "      " << Array[i].y << endl;
  56.     }
  57. }
  58. double DividedDifference(int i, Node* Array)
  59. { // Разделенная разность
  60.     double DD = 0;
  61.     for (int j = 0; j <= i; j++)
  62.     {
  63.         double tmp = 1;
  64.         for (int k = 0; k <= i; k++)
  65.         {
  66.             if (k != j)
  67.                 tmp *= Array[j].x - Array[k].x;
  68.         }
  69.         DD += Array[j].y / tmp;
  70.     }
  71.  
  72.     return DD;
  73. }
  74.  
  75. void ValueChebyshevTable(functiontype* f, Node* Array, double Initial, double End, int Count)
  76. { // Создание таблицы Чебышевских значений
  77.     for (int i = 0; i < Count; i++)
  78.     {
  79.         Array[i].x = ((End + Initial) / 2)
  80.             + ((End - Initial) / 2) * cos(((2 * i + 1) * PI) / (2 * (Count + 1)));
  81.         Array[i].y = (*f)(Array[i].x);
  82.     }
  83. }
  84.  
  85. void get_koef_polynom(double* mas, double* res, int n, int k)
  86. { // Функция на вход берет массив из n-1 точек и
  87.   // возвращает кф полином получившегося при
  88.   // раскрытии скобок !!!(И еще надо домножить на
  89.   // игрик)!!!
  90.     int i;
  91.     double* anx = new double[n + 5];
  92.     double* ann = new double[n + 5];
  93.     res[0] = mas[0];
  94.     res[1] = 1;
  95.     int j;
  96.     for (j = 0; j <= n; j++)
  97.     {
  98.         anx[j] = 0.0;
  99.     }
  100.  
  101.     for (j = 0; j < n; j++)
  102.     {
  103.         ann[j] = 0.0;
  104.     }
  105.     for (i = 1; i < k; i++) //считаем коэффициенты
  106.         for (j = 0; j <= i + 1; j++)
  107.         {
  108.             anx[j + 1] = res[j];
  109.             ann[j] = res[j] * mas[i];
  110.             res[j] = anx[j] + ann[j];
  111.         }
  112. }
  113.  
  114. //Возвращает число, возведенное в cтепень i
  115. double get_degree(double x, int degree) {
  116.     int i;
  117.     double y = x;
  118.     if (degree == 0)
  119.         return 1;
  120.  
  121.     for (i = 0; i < degree - 1; i++)
  122.         y *= x;
  123.     return y;
  124. }
  125.  
  126. double round(double x) {
  127.     if (x < 0.0000000001)
  128.         x = 0.0;
  129.     return x;
  130. }
  131.  
  132. // Полином Лагранжа в точке
  133. double PolynomLG_dot(double x, Node *Array, int Count)
  134. {
  135.     double Polynom = 0;
  136.     for (int i = 0; i < Count; i++)
  137.     { // Счетчик по функциям l_i
  138.         double Li = 1;
  139.         for (int j = 0; j < Count; j++)
  140.         { // Счетчик по x_j
  141.             if (i != j) Li *= (x - Array[j].x) / (Array[i].x - Array[j].x);
  142.         }
  143.         Polynom += Array[i].y * Li;
  144.     }
  145.     return Polynom;
  146. }
  147.  
  148. //Полином Ньютона в точке
  149. double PolynomN_dot(double x, Node *Array, int Count)
  150. {
  151.     double Result = Array[0].y, dd;
  152.     for (int i = 1; i < Count; i++)
  153.     {
  154.         dd = 0.0;
  155.         dd=DividedDifference(i, Array);
  156.         for (int k = 0; k < i; k++) dd = dd * (x - Array[k].x);
  157.         Result += dd; // Домножаем разделенную разность на скобки (x-x[0])...(x-x[i-1])
  158.     }
  159.    
  160.     return Result;
  161. }
  162.  
  163. //Подходит для построенных полиномов, считает их знач в данных нам n узлах, но если их слишком мало? Надо добавить!
  164. void table_in_file(Node* Array, int n, int z, double* polynom_koeff, string file_name, string file_name_pogr) { // Функция берет таблицу иксов и игриков, количество точек в которых считаем знач полинома (мб убрать) и коэфф полинома,
  165.                                                                 // По итоге имеем файл с 2 столбацами: х и у, по которому гну пло
  166.     int k, j;
  167.     double y_value, x_value;
  168.  
  169.     ofstream fout(file_name);
  170.     ofstream pogr(file_name_pogr);
  171.  
  172.  
  173.     for (k = 0; k < n; k++) { //n иксов подставляев в полином степени n-1
  174.         x_value = Array[k].x;
  175.         fout << x_value << " ";
  176.         pogr << x_value << " ";
  177.         y_value = 0.0;
  178.         for (j = 0; j < z; j++) { //убрал n+1 потому что вылезал за границы памяти но поч так хз
  179.             //cout << "x: " << x_value << " ";
  180.             //cout << polynom_koeff[j] << " ";
  181.             //cout << "x: ^  " << get_degree(x_value, j) << " ";  //Чтобы не умножать ахуенно маленькое число на икс в большой степени надо знать какой степени у нас многочлен , а то e^-17 умножаем на x^10
  182.             y_value += polynom_koeff[j] * get_degree(x_value, j); //На 0 индексе стоит свободные член, умножаем на икс в 0 стпени = 1
  183.             //cout << y_value << endl << endl << endl;
  184.  
  185.         }
  186.         fout << y_value << endl;
  187.         //cout << "y_value: " << y_value << endl;
  188.         //cout << "Array[k].y: " << Array[k].y << endl;
  189.         //cout << "Array[k].y - y_value:  " << Array[k].y - y_value << endl;
  190.  
  191.         pogr << abs(y_value - Array[k].y) << endl;
  192.  
  193.     }
  194.  
  195.     fout.close();
  196. }
  197.  
  198. //То же самое но значение считает сразу вточке
  199. void table_in_file2(Node* MyArray, Node* Array, int n,int z, string file_name, string file_name_pogr, string method_name) { // Функция берет таблицу иксов и игриков, количество точек в которых считаем знач полинома (мб убрать) и коэфф полинома,
  200.                                                                 // По итоге имеем файл с 2 столбацами: х и у, по которому гну пло
  201.     int k, j;
  202.     double y_value, x_value;
  203.  
  204.     ofstream fout(file_name);
  205.     ofstream pogr(file_name_pogr);
  206.  
  207.  
  208.  
  209.  
  210.     for (k = 0; k < n; k++) { //n иксов подставляев в полином степени n-1
  211.         x_value = MyArray[k].x;
  212.         fout << x_value << " ";
  213.         pogr << x_value << " ";
  214.  
  215.         if (method_name == "Lagrange")
  216.             y_value = PolynomLG_dot(x_value, Array, z);
  217.         else
  218.             y_value = PolynomN_dot(x_value, Array, z);
  219.  
  220.         fout << y_value << endl;
  221.        
  222.         pogr << abs(y_value - MyArray[k].y) << endl;
  223.  
  224.     }
  225.  
  226.     fout.close();
  227. }
  228.  
  229. void orig_table_in_file(Node* Array, int n) { // Функция берет таблицу иксов и игриков, количество точек в которых считаем знач полинома (мб убрать) и коэфф полинома,
  230.                                                                        // По итоге имеем файл с 2 столбацами: х и у, по которому гну пло
  231.     int k;
  232.     double y_value, x_value;
  233.  
  234.     ofstream fout("D:/Original_graphic.txt");
  235.  
  236.     for (k = 0; k < n; k++) { //n иксов подставляев в полином степени n-1
  237.         x_value = Array[k].x;
  238.         fout << x_value << " ";
  239.         y_value = Array[k].y;
  240.         fout << y_value << endl;
  241.     }
  242.  
  243.     fout.close();
  244. }
  245.  
  246.  
  247.  
  248. double W(double x, int n, Node* Array)
  249. { // Полином вида: (x - x1) * (x - x2) * ... * (x - xn)
  250.     double w = 1;
  251.     for (int i = 1; i <= n; i++)
  252.     {
  253.         w *= x - Array[i].x;
  254.     }
  255.     return w;
  256. }
  257.  
  258.  
  259.  
  260. void ApproximateError(functiontype *Function, double Initial, double End, Node *Array, int Count)
  261. { // Приближенная погрешность
  262.  
  263.     for (double x = Initial; x <= End; x += 0.01f)
  264.     {
  265.         abs(exp(End) * W(x, Count, Array) / Factorial(Count + 1));
  266.         abs(exp(End) * W(x, Count, Array) / Factorial(Count + 1));
  267.     }
  268. }
  269.  
  270. void PolynomLG(Node* Array, int n, double* &konmas)
  271. {
  272.     int i, j, l, p, z, c;
  273.     double* massiv2 = new double[n]; // массив А0...An конечных коэфф для одного
  274.                                      // шага цикла сколько точек, столько и коэфф
  275.     double* massiv = new double[n - 1]; //массив X0,,без Хi,Хn домноженных на коэфф.  ПОЭТОМУ Н-1
  276.     //double* konmas = new double[n]; // будет коннечный массив коэфф      
  277.     double k;
  278.     for (j = 0; j < n; j++)
  279.     {
  280.         konmas[j] = 0.0;
  281.     }
  282.     for (i = 0; i < n; i++)
  283.     {
  284.         c = 0;
  285.         for (j = 0; j < n - 1; j++)
  286.         {
  287.             massiv[j] = 0.0;
  288.             massiv2[j] = 0.0;
  289.         }
  290.         massiv2[n - 1] = 0.0;
  291.         k = Array[i].y;
  292.         for (p = 0; p < n; p++)
  293.         {
  294.             if (p != i)
  295.             {
  296.                 k *= 1.0 / (Array[i].x - Array[p].x);
  297.                 massiv[c] = 0.0 - Array[p].x;
  298.                 c++;
  299.             }
  300.         }
  301.         cout << endl;
  302.         get_koef_polynom(massiv, massiv2, n - 1, n - 1);
  303.         for (l = 0; l < n; l++)
  304.         {
  305.             konmas[l] += massiv2[l] * k;
  306.         }
  307.         /*cout << "konmas  ";
  308.         for (z = 0; z < n; z++)
  309.         {
  310.             cout << konmas[z] << ' ';
  311.         }*/
  312.     }
  313.  
  314.     //table_in_file(Array, n, konmas); //                    
  315.     cout << endl;
  316. }
  317.  
  318.  
  319. void PolynomN(Node* Array, int n, double* &konmas)
  320. {
  321.     int j;
  322.     double dd;
  323.     double* massiv2 = new double[n]; // массив А0...An конечных коэфф для одного
  324.                                      // шага цикла сколько точек, столько и коэфф
  325.     double* massiv = new double[n - 1]; //массив X0,,,Хn                 +1 для зануления
  326.     //double* konmas = new double[n]; // будет коннечный массив коэфф
  327.     int i;
  328.  
  329.     for (int j = 0; j < n - 1; j++)
  330.     {
  331.         konmas[j] = 0.0;
  332.         massiv[j] = 0.0;
  333.     }
  334.  
  335.     konmas[n - 1] = 0.0;
  336.  
  337.     for (int j = 0; j < n - 1; j++)
  338.     { //Кладем все иксы
  339.         massiv[j] = 0.0 - Array[j].x;
  340.     }
  341.  
  342.     konmas[0] = Array[0].y; // 0 индекс хранит свободный член итого многочлена
  343.  
  344.     for (i = 1; i < n; i++)
  345.     {
  346.         for (j = 0; j < n; j++)
  347.         {
  348.             massiv2[j] = 0.0;
  349.         }
  350.  
  351.         dd = DividedDifference(i, Array); //Ищем итую РР
  352.     //  cout << "DD " << dd << endl << endl;
  353.         get_koef_polynom(massiv, massiv2, n - 1,
  354.             i); //Возвращает кф при перемножении (х-Х0)...(х-Хi+1),
  355.         for (j = 0; j < n; j++)
  356.         {
  357.             konmas[j] += massiv2[j] * dd;
  358.  
  359.         }
  360.  
  361.         cout << endl;
  362.  
  363.         cout << endl;
  364.     }
  365.  
  366.     /*for (j = 0; j < n; j++)
  367.     {
  368.         konmas[j] = round(konmas[j]);
  369.         cout << konmas[j] << "   ";
  370.     }*/
  371.     cout << endl;
  372.  
  373.  
  374. }
  375.  
  376. double DFunc(functiontype* func, double x,
  377.     int n) //возварщает проивзодную нго порядка как константу типа дабл
  378. { // Производная функции
  379.     double h = 0.00001;
  380.     if (n == 1)
  381.     {
  382.         return ((*func)(x + h) - (*func)(x)) / h;
  383.     }
  384.     else
  385.     {
  386.         return (DFunc(func, x + h, n - 1) - DFunc(func, x, n - 1)) / h;
  387.     }
  388. }
  389.  
  390. double test(functiontype* func, double x, int n, long double h)
  391. { // Производная функции
  392.     h = 0.0001;
  393.     while (n > 1)
  394.     {
  395.         return (test(func, x + h, n - 1, h / pow(10, -2))
  396.             - test(func, x - h, n - 1, h / pow(10, -2)))
  397.             / 2 * h;
  398.     }
  399.     if (n == 1)
  400.     {
  401.         return ((*func)(x + h) - (*func)(x - h)) / 2 * h;
  402.     }
  403. }
  404.  
  405.  
  406.  
  407. int main()
  408. {
  409.  
  410.     setlocale(LC_ALL, "RUS");
  411.  
  412.     //ПОСТРОЕНИЕ ДАННЫХ
  413.     Interval Interval;
  414.     int CountNodes, MyNodes = 100;
  415.     functiontype Func = &Myfunk;
  416.  
  417.     /*cout << "Enter the interval: " << endl;
  418.     cin >> Interval.InitialNode >> Interval.EndNode;
  419.     cout << "Enter the number of nodes: " << endl;
  420.     cin >> CountNodes;*/
  421.  
  422.     //Ввод вручную
  423.     Interval.InitialNode = -5;
  424.     Interval.EndNode = 5;
  425.     CountNodes = 25;
  426.  
  427.     double* konmasNew = new double[CountNodes];
  428.     double* konmasLag = new double[CountNodes];
  429.     Node *ArrayUniformNodes = new Node[CountNodes];// Массив с равномерными // узлами
  430.     Node *ArrayUniformNodes2 = new Node[MyNodes];
  431.     //Node* ArrayChebyshevNodes = new Node[CountNodes]; // Массив с Чебышевскими узлами
  432.     Node *ArrayformNodes2 = new Node[100]; //Массив где будет много точек для построение ориг графика
  433.  
  434.     ValueUniformTable(&Func, ArrayUniformNodes, Interval.InitialNode, Interval.EndNode, CountNodes); // Заполнение таблицы равномерных значений
  435.     ValueUniformTable(&Func, ArrayUniformNodes2, Interval.InitialNode, Interval.EndNode, MyNodes);
  436.     //ValueChebyshevTable(&Func, ArrayChebyshevNodes, Interval.InitialNode, Interval.EndNode, CountNodes); // Заполнение таблицы Чебышевских значений
  437.  
  438.  
  439.     // ЗАПУСКИ ФУНКЦИЙ
  440.     //cout << "Лагранж в точке:" << PolynomN_dot(-0.46, ArrayUniformNodes, CountNodes);
  441.  
  442.  
  443.     cout << endl;
  444.     //PolynomLG(ArrayUniformNodes, CountNodes, konmas);
  445.     cout << endl;
  446.     //PolynomN(ArrayUniformNodes, CountNodes,konmas);
  447.     table_in_file2(ArrayUniformNodes2, ArrayUniformNodes, MyNodes, CountNodes, "D:/Lagrange.txt", "D:/Pogr_Lagrange.txt", "Lagrange");
  448.     table_in_file2(ArrayUniformNodes2, ArrayUniformNodes, MyNodes, CountNodes, "D:/Newton.txt", "D:/Pogr_Newton.txt", "oNewtn");
  449.     //table_in_file(ArrayUniformNodes2, MyNodes, CountNodes, konmasLag, "D:/whithLag.txt", "D:/Pogr_withLag.txt");
  450.     //table_in_file(ArrayUniformNodes2, MyNodes, CountNodes, konmasNew, "D:/withNew.txt", "D:/Pogr_withNew.txt");
  451.     orig_table_in_file(ArrayUniformNodes2, MyNodes);
  452.  
  453.  
  454.     // Абсолютная погрешность
  455.     //AbsoluteError(&Func, Interval.InitialNode, Interval.EndNode, ArrayUniformNodes, CountNodes);
  456.     // Приближенная погрешность
  457.     //ApproximateError(&Func, Interval.InitialNode, Interval.EndNode, ArrayUniformNodes, CountNodes);
  458.  
  459.     //system("pause");
  460.     return 0;
  461. }
Advertisement
Add Comment
Please, Sign In to add comment