Advertisement
rfq

Untitled

rfq
May 10th, 2023 (edited)
445
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. void natural_cubic_spline(double x[], double a[], int n, double b[], double c[], double d[]) {
  6.     double h[n], alfa[n], l[n+1], myu[n], z[n+1];
  7.  
  8.     // Step 1:
  9.     for (int i = 0; i < n; i++) {
  10.         h[i] = x[i+1] - x[i];
  11.     }
  12.  
  13.     // Step 2
  14.     for (int i = 1; i < n; i++) {
  15.         alfa[i] = (3/h[i])*(a[i+1]-a[i]) - (3/h[i-1])*(a[i]-a[i-1]);
  16.     }
  17.  
  18.     // Step 3
  19.     l[0] = 1;
  20.     myu[0] = 0;
  21.     z[0] = 0;
  22.  
  23.     // Step 4
  24.     for (int i = 1; i < n; i++) {
  25.         l[i] = 2*(x[i+1]-x[i-1]) - h[i-1]*myu[i-1];
  26.         myu[i] = h[i] / l[i];
  27.         z[i] = (alfa[i] - h[i-1]*z[i-1]) / l[i];
  28.     }
  29.  
  30.     // Step 5
  31.     l[n] = 1;
  32.     z[n] = 0;
  33.     c[n] = 0;
  34.  
  35.     // Step 6
  36.     for (int j = n-1; j >= 0; j--) {
  37.         c[j] = z[j] - myu[j]*c[j+1];
  38.         b[j] = (a[j+1]-a[j])/h[j] - h[j]*(c[j+1]+2*c[j])/3;
  39.         d[j] = (c[j+1]-c[j])/(3*h[j]);
  40.     }
  41.  
  42.     // Print the results
  43.     cout << "\nj" << "\tx[j]" << "\ta[j]" << "\t\tb[j]" << "\t\tc[j]" << "\t\td[j]";
  44.     for (int j = 0; j < n; j++) {
  45.         cout << "\n" << j << "\t" << x[j] << "\t" << a[j] << "\t\t" << b[j] << "\t\t" << c[j] << "\t\t" << d[j];
  46.     }
  47. }
  48.  
  49. int main() {
  50.   double x[100] = {0.9, 1.3, 1.9, 2.1, 2.6, 3.0, 3.9, 4.4, 4.7, 5.0, 6.0, 7.0, 8.0, 9.2, 10.5, 11.3, 11.6, 12.0, 12.6, 13.0, 13.3};
  51.   double y[100] = {1.3, 1.5, 1.85, 2.1, 2.6, 2.7, 2.4, 2.15, 2.05, 2.1, 2.25, 2.3, 2.25, 1.95, 1.4, 0.9, 0.7, 0.6, 0.5, 0.4, 0.2};
  52.  
  53.   int n = 21; // panjang array diatas.
  54.  
  55.   double b[n], c[n+1], d[n];
  56.  
  57.   natural_cubic_spline(x, y, n, b, c, d);
  58.  
  59.   return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement