Advertisement
cd62131

Chebyshev polynomial interpolation

Dec 4th, 2017
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.41 KB | None | 0 0
  1. #define _USE_MATH_DEFINES
  2. #include <math.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. static double x(int i, int n);
  7. static double w(int n);
  8. static double lambda_inv(int k);
  9. static double T(int k, double x);
  10. static double f(double x);
  11. static double c(int k, int n);
  12. static double f_interpolation(int n, double x);
  13.  
  14. static double x(int i, int n) {
  15.   return cos(M_PI_2 / n * (2 * i - 1));
  16. }
  17.  
  18. static double w(int n) {
  19.   return M_PI / n;
  20. }
  21.  
  22. static double lambda_inv(int k) {
  23.   return (k == 0) ? M_1_PI : M_2_PI;
  24. }
  25.  
  26. static double T(int k, double x) {
  27.   return (k == 0) ? 1 : (k == 1) ? x : 2 * x * T(k - 1, x) - T(k - 2, x);
  28. }
  29.  
  30. static double f(double x) {
  31.   return 1. / (1 + 25 * x * x);
  32. }
  33.  
  34. static double c(int k, int n) {
  35.   double sum = 0.;
  36.   for (int i = 1; i <= n; ++i) {
  37.     double xi = x(i, n);
  38.     sum += w(n) * T(k, xi) * f(xi);
  39.   }
  40.   return lambda_inv(k) * sum;
  41. }
  42.  
  43. static double f_interpolation(int n, double x) {
  44.   double sum = 0.;
  45.   for (int k = 0; k < n; ++k) {
  46.     sum += c(k, n) * T(k, x);
  47.   }
  48.   return sum;
  49. }
  50.  
  51. int main(void) {
  52.   FILE *out;
  53.   char name[BUFSIZ];
  54.   int ns[] = { 5, 9, 17 };
  55.   for (size_t i = 0; i < sizeof(ns) / sizeof(ns[0]); ++i) {
  56.     sprintf(name, "%d.dat", ns[i]);
  57.     out = fopen(name, "w");
  58.     for (int x = -100; x <= 100; ++x) {
  59.       double xi = x / 100.;
  60.       fprintf(out, "%lf %lf\n", xi, f_interpolation(ns[i], xi));
  61.     }
  62.     fclose(out);
  63.   }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement