Advertisement
kasper_k

InterLagrange

Oct 27th, 2022 (edited)
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. #include <iostream>
  2. #include <conio.h>
  3.  
  4. using namespace std;
  5.  
  6. double my_lagrange(double x, int n, double x_arr[], double y_arr[]);
  7.  
  8. int main()
  9. {
  10.  
  11.     int n = 5;
  12.  
  13.     double x_arr[5] = {0.079, 0.637, 1.345, 2.095, 2.782};
  14.     double y_arr[5] = {-4.308, -0.739, 1.697, 4.208, 6.203};
  15.  
  16.     for (double x = 0; x < 3; x += 1) {
  17.         cout << "f(" << x << ") = "
  18.             << my_lagrange(x, n, x_arr, y_arr) << endl;
  19.  
  20.     }
  21.  
  22.     system("pause");
  23.     return 0;
  24. }
  25.  
  26. double my_lagrange(double x, int n, double x_arr[], double y_arr[]) {
  27.     //Пусть точки отсортированы по возрастанию координаты x
  28.  
  29.     if (n > 5)
  30.         return (x <= x_arr[n / 2]) ? my_lagrange(x, (n + 1) / 2, x_arr, y_arr) :
  31.         my_lagrange(x, (n + 1) / 2, &x_arr[n / 2], &y_arr[n / 2]);
  32.  
  33.     double sum = 0;
  34.     for (int i = 0; i < n; ++i) {
  35.  
  36.         double l = 1;
  37.         for (int j = 0; j < n; ++j)
  38.             if (j != i)
  39.                 l *= (x - x_arr[j]) / (x_arr[i] - x_arr[j]);
  40.         sum += y_arr[i] * l;
  41.     }
  42.  
  43.     return sum;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement