Advertisement
Guest User

Untitled

a guest
May 22nd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. using namespace std;
  5.  
  6. double f(double x){
  7.     return 2*x*x - x + 3;
  8. }
  9.  
  10. double df(double x){
  11.     return 4*x - 1;
  12. }
  13.  
  14. double L(double x, int n, double x_arr[], double y_arr[]){
  15.    
  16.     double sum = 0;
  17.     for (int i = 0; i < n; ++i){
  18.        
  19.         double l = 1;
  20.         for (int j = 0; j < n; ++j)
  21.             if (j != i)
  22.                 l *= (x - x_arr[j]) / (x_arr[i] - x_arr[j]);
  23.         sum += y_arr[i] * l;
  24.     }
  25.    
  26.     return sum;
  27. }
  28.  
  29. double dL(double x, int n, double x_arr[], double y_arr[]){
  30.    
  31.     double sum1 = 0;
  32.     for (int i = 0; i < n; ++i){
  33.        
  34.         double sum2 = 0;
  35.         for (int j = 0; j < n; ++j){
  36.             if (j != i){
  37.                 double p = 1;
  38.                 for (int k = 0; k < n; ++k)
  39.                     if (k != i && k != j)
  40.                         p *= (x - x_arr[k]) / (x_arr[i] - x_arr[k]);                    
  41.                 sum2 += p/(x_arr[i] - x_arr[j]);
  42.             }          
  43.         }
  44.         sum1 += y_arr[i]*sum2;
  45.     }
  46.    
  47.     return sum1;
  48. }
  49.  
  50. int main(){
  51.    
  52.     const int N = 3;
  53.    
  54.     double x_arr[N], y_arr[N];
  55.     for (int i = 0; i < N; ++i){
  56.         x_arr[i] = 2*i;
  57.         y_arr[i] = f(x_arr[i]);
  58.     }
  59.    
  60.     cout << setw(3) << "x";
  61.     cout << setw(10) << "f(x)";
  62.     cout << setw(10) << "L(x)";
  63.     cout << setw(10) << "df(x)";
  64.     cout << setw(10) << "dL(x)" << endl;
  65.        
  66.     for (int i = 0; i < 20; ++i){
  67.         double x = i;
  68.         cout << setw(3) << x;
  69.         cout << setw(10) << setprecision(6) << f(x);
  70.         cout << setw(10) << setprecision(6) << L(x, N, x_arr, y_arr);
  71.         cout << setw(10) << setprecision(6) << df(x);      
  72.         cout << setw(10) << setprecision(6) << dL(x, N, x_arr, y_arr);
  73.         cout << endl;
  74.     }  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement