Advertisement
Vladislav_Bezruk

Untitled

Nov 13th, 2021
729
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.86 KB | None | 0 0
  1. #include <iostream>
  2. #include <cassert>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. double lagrangeInterp(double x[], double y[], int n, double xL) {
  8.     double sum = 0, mult;
  9.    
  10.     for (int i = 0; i < n; i++) {
  11.         mult = 1;
  12.        
  13.         for (int j = 0; j < n; j++) {
  14.             if (i != j) {
  15.                 assert(fabs(x[i] - x[j]) > 1e-10 && "Сannot be divided by zero!");
  16.                
  17.                 mult *= (xL - x[j]) / (x[i] - x[j]);
  18.             }
  19.         }
  20.        
  21.         sum += mult * y[i];
  22.     }
  23.    
  24.     return sum;
  25. }
  26.  
  27. int main() {
  28.  
  29.     int n;
  30.    
  31.     cout << "Enter count of points: ";
  32.     cin >> n;
  33.    
  34.     double x[n], y[n], xL;
  35.    
  36.     cout << "Enter x array: ";
  37.    
  38.     for (int i = 0; i < n; i++) {
  39.         cin >> x[i];
  40.     }
  41.    
  42.     cout << "Enter y array: ";
  43.    
  44.     for (int i = 0; i < n; i++) {
  45.         cin >> y[i];
  46.     }
  47.  
  48.     cout << "Enter x to find f(x): ";
  49.     cin >> xL;
  50.    
  51.     cout << "f(" << xL << ") = " << lagrangeInterp(x, y, n, xL) << endl;
  52.    
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement