Advertisement
MeShootIn

Polynomial interpolation

Apr 25th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. double binary_power(double a, int n){
  8.     if(n == 0){
  9.         return 1;
  10.     }
  11.    
  12.     if(n % 2 == 0){
  13.         double res = binary_power(a, n / 2);
  14.        
  15.         return res * res;
  16.     }
  17.     return a * binary_power(a, n - 1);
  18. }
  19.  
  20. void fill_X(vector < vector <double> > & X, vector <double> & x){
  21.     int N = X.size();
  22.    
  23.     for(int i = 0; i < N; ++i){
  24.         for(int j = 0; j < N; ++j){
  25.             X[i][j] = binary_power(x[i], N - j - 1);
  26.         }
  27.     }
  28. }
  29.  
  30. void triangulation(vector < vector <double> > & A, vector <double> & b){
  31.     int N = A.size();
  32.    
  33.     for(int j = 0; j < N; ++j){
  34.         if(A[j][j] == 0){
  35.             int index = 0;
  36.             for(int i = 1; i < N; ++i){
  37.                 if(fabs(A[i][j]) > A[index][j] && A[i][j] != 0){
  38.                     index = i;
  39.                 }
  40.             }
  41.             swap(A[j], A[index]);
  42.             swap(b[j], b[index]);
  43.         }
  44.         for(int i = j + 1; i < N; ++i){
  45.             double m = A[i][j] / A[j][j];
  46.             for(int k = j; k < N; ++k){
  47.                 A[i][k] -= m * A[j][k];
  48.             }
  49.             b[i] -= m * b[j];
  50.         }
  51.     }
  52. }
  53.  
  54. void solve(vector < vector <double> > & A, vector <double> & x, vector <double> & b){
  55.     int N = A.size();
  56.    
  57.     for(int i = N - 1; i >= 0; --i){
  58.         double Sum = 0;
  59.         for(int j = i + 1; j < N; ++j){
  60.             Sum += A[i][j] * x[j];
  61.         }
  62.         x[i] = (b[i] - Sum) / A[i][i];
  63.     }
  64. }
  65.  
  66. int main(){
  67.     cout << "Enter the number of points:\n";
  68.     int N;
  69.     cin >> N;
  70.    
  71.     vector <double> x(N);
  72.     vector <double> y(N);
  73.    
  74.     cout << "Enter " << N << " pairs of coordinates (x, y):\n";
  75.     for(int i = 0; i < N; ++i){
  76.         cin >> x[i] >> y[i];
  77.     }
  78.    
  79.     vector < vector <double> > X(N, vector <double> (N));
  80.     fill_X(X, x);
  81.    
  82.     vector <double> a(N);
  83.    
  84.     triangulation(X, y);
  85.     solve(X, a, y);
  86.    
  87.     cout << "Polynomial coefficients (starting from the highest power):\n";
  88.     for(int i = 0; i < N; ++i){
  89.         cout << a[i] << " ";
  90.     }
  91.     cout << "\n";
  92.    
  93.     system("PAUSE");
  94.     return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement