Advertisement
MeShootIn

Lagrange polynomial

Jun 22nd, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. double P(double x0, vector <double> x, vector <double> y){
  7.     int N = x.size();
  8.     double S = 0;
  9.    
  10.     for(int i = 0; i < N; ++i){
  11.         double L = 1;
  12.        
  13.         for(int j = 0; j < N; ++j){
  14.             if(i != j){
  15.                 L *= (x0 - x[j]) / (x[i] - x[j]);
  16.             }
  17.         }
  18.        
  19.         S += y[i] * L;
  20.     }
  21.    
  22.     return S;
  23. }
  24.  
  25. vector <double> get_coefficients(vector <double> x, vector <double> y){
  26.     int N = x.size();
  27.     vector <double> a(N);
  28.    
  29.     for(int i = 0; i < N; ++i){
  30.         a[i] = y[i];
  31.         for(int j = 0; j < N; ++j){
  32.             if(i != j){
  33.                 a[i] /= x[i] - x[j];
  34.             }
  35.         }
  36.     }
  37.    
  38.     return a;
  39. }
  40.  
  41. int main(){
  42.     int N;
  43.     cin >> N;
  44.    
  45.     vector <double> x(N);
  46.     vector <double> y(N);
  47.    
  48.     for(int i = 0; i < N; ++i){
  49.         cin >> x[i] >> y[i];
  50.     }
  51.    
  52.     for(auto a : get_coefficients(x, y)){
  53.         cout << a << " ";
  54.     }
  55.    
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement