Advertisement
Vladislav_Bezruk

Untitled

Dec 12th, 2021
536
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.57 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. double lagrangeInterp(double x[], double y[], int n, double x0) {
  7.     double sum = 0, mult;
  8.  
  9.     for (int i = 0; i < n; i++) {
  10.         mult = 1;
  11.  
  12.         for (int j = 0; j < n; j++)
  13.             if (i != j)
  14.                 mult *= (x0 - x[j]) / (x[i] - x[j]);
  15.         sum += mult * y[i];
  16.     }
  17.  
  18.     return sum;
  19. }
  20.  
  21. int main() {
  22.  
  23.     const int n = 5;
  24.     double x0;
  25.  
  26.     double x[n]  {0, 1, 2, 3, 4};
  27.     double y[n]  {1, -1, 0, 10, 35};
  28.  
  29.     cout << "Enter x: ";
  30.     cin >> x0;
  31.  
  32.     cout << "f(" << x0 << ") = " << lagrangeInterp(x, y, n, x0) << endl;
  33.  
  34.     return 0;
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement