# One Dimensional Interpolation: Introduction and Implementation in Ruby

Interpolation involves predicting the co-ordinates of a point given the co-ordinates of points around it. Interpolation can be done in one or more dimensions. In this article I will give you a brief introduction of one-dimensional interpolation and execute it on a sample data set using the interpolation gem.

One dimensional interpolation involves considering consecutive points along the X-axis with known Y co-ordinates and predicting the Y co-ordinate for a given X co-ordinate.

There are several types of interpolation depending on the number of known points used for predicting the unknown point, and several methods to compute them, each with their own varying accuracy. Methods for interpolation include the classic Polynomial interpolation with Lagrange’s formula or spline interpolation using the concept of spline equations between points.

The spline method is found to be more accurate and hence that is what is used in the interpolation gem.

## Common Interpolation Routines

Install the interpolation gem with gem install interpolation. Now lets see a few common interpolation routines and their implementation in Ruby:

#### Linear Interpolation

This is the simplest kind of interpolation. It involves simply considering two points such that x[j] < num < x[j+1], where num is the unknown point, and considering the slope of the straight line between (x[j], y[j] ) and (x[j+1], y[j+1]), predicts the Y co-ordinate using a simple linear polynomial.

Linear interpolation uses this equation:

Here interpolant is the value of the X co-orinate whose corresponding Y-value needs to found.

Ruby code:

 1 2 3 4 5 6 7 8 9  require 'interpolation' x = (0..100).step(3).to_a y = x.map { |a| Math.sin(a) } int = Interpolation::OneDimensional.new x, y, type: :linear int.interpolate 35 # => -0.328 

#### Cubic Spline Interpolation

Cubic Spline interpolation defines a cubic spline equation for each set of points between the 1st and nth points. Each equation is smooth in its first derivative and continuos in its second derivative.

So for example, if the points on a curve are labelled i, where i = 1..n, the equations representing any two points i and i-1 will look like this:

Cubic spline interpolation involves finding the second derivative of all points $y_{i}$, which can then be used for evaluating the cubic spline polynomial, which is a function of x, y and the second derivatives of y.

 1 2 3 4 5 6 7 8 9  require 'interpolation' x = (0..9).step(1).to_a y = x.map { |e| Math.exp(e) } f = Interpolation::OneDimensional.new(@x, @y, type: :cubic, sorted: true) f.interpolate(2.5) # => 12.287