GNU Scientific Library – Reference Manual: Chebyshev Approximation Examples

Next: Chebyshev Approximation References and Further Reading, Previous: Derivatives and Integrals, Up: Chebyshev Approximations [Index]

### 29.6 Examples

The following example program computes Chebyshev approximations to a step function. This is an extremely difficult approximation to make, due to the discontinuity, and was chosen as an example where approximation error is visible. For smooth functions the Chebyshev approximation converges extremely rapidly and errors would not be visible.

    #include <stdio.h>
    #include <gsl/gsl_math.h>
    #include <gsl/gsl_chebyshev.h>

    double
    f (double x, void *p)
    {
      if (x < 0.5)
        return 0.25;
      else
        return 0.75;
    }

    int
    main (void)
    {
      int i, n = 10000;

      gsl_cheb_series *cs = gsl_cheb_alloc (40);

      gsl_function F;

      F.function = f;
      F.params = 0;

      gsl_cheb_init (cs, &F, 0.0, 1.0);

      for (i = 0; i < n; i++)
        {
          double x = i / (double)n;
          double r10 = gsl_cheb_eval_n (cs, 10, x);
          double r40 = gsl_cheb_eval (cs, x);
          printf ("%g %g %g %g\n",
                  x, GSL_FN_EVAL (&F, x), r10, r40);
        }

      gsl_cheb_free (cs);

      return 0;
    }

The output from the program gives the original function, 10-th order approximation and 40-th order approximation, all sampled at intervals of 0.001 in x.