←to practical programming

Homework "Splines"

Objective: Implement functions for interpolation of tabulated data.
  1. (6 points) Linear spline (linear interpolation)

    1. Implement a function that makes linear spline interpolation from a table {x[i], y[i]} at a given point z. Here you don't need to either pre-calculate anything or use any structs. The signature of your function should be something like
      public static double linterp(double[] x, double[] y, double z){
              int i=binsearch(x,z);
              double dx=x[i+1]-x[i]; if(!(dx>0)) throw new Exception("uups...");
              double dy=y[i+1]-y[i];
              return y[i]+dy/dx*(z-x[i]);
              }
      
      Location of the index i of the interval containing z, x[i]<z<x[i+1], must(!) be done using binary search, like this:
      public static int binsearch(double[] x, double z)
      	{/* locates the interval for z by bisection */ 
      	if(!(x[0]<=z && z<=x[x.Length-1])) throw new Exception("binsearch: bad z");
      	int i=0, j=x.Length-1;
      	while(j-i>1){
      		int mid=(i+j)/2;
      		if(z>x[mid]) i=mid; else j=mid;
      		}
      	return i;
      	}
      
    2. Implement a function that calculates the intergral of the linear spline from the point x[0] to the given point z. The integral must be calculated analytically as it is an integral of a linear function. The signature could be something like

      double linterpInteg(double[] x, double[] y, double z)
      
    3. Make some indicative plots to prove that your linear spline and your integrator work as intended.

  2. (3 points) Quadratic spline

    Implement quadratic spline with derivative and integral. Note that quadratic spline is only for learning, for practical applications always use cubic spline instead.

    Hints:

  3. (1 points) Cubic spline

Hints:

  1. You can use either our vector class or double[] to keep the data.

  2. Programming styles:

    The exercise can be solved using different styles of programming:

    1. Object oriented programming: The structure (or class) holds both the data and the appropriate functions (called member functions) which have direct access to the data in the structure.

    2. Functional programming: The function for spline-evaluation is created and returned. This function captures all the needed information in itself (in its environment, to be precise).

  3. The plots can be done using either Pyxplot/Gnuplot or the "quick-and-dirty" plotter, the graph utility from plotutils. Install it with sudo apt-get install plotutils. It is a simple filter which takes data in the form of two columns, for x and y, from the standard input (or from a file) and sends a plot in the given format to the standard output, for example,
    graph --output-format svg < data > plot.svg
    
    A blank line in the data-file separates different data sets.