Path: blob/master/material/interpolation.ipynb
934 views
Interpolation Methods
Due to the discrete, and sometimes sparse, nature of experiments and observations, data taking procedures will always produce discrete data as well. Even, as we have seen before, information only can be discretely presented into a computer due to the binary representation. However, when we are dealing with physical models, continuous and smooth properties are of course preferred. Interpolation techniques allow then to recover a continuous field from sparse datasets. Throughout this section we shall cover some of these interpolation methods.
Bibliography:
[1a] Gonzalo Galiano Casas, Esperanza García Gonzalo Numerical Computation - GD - Web page with notebooks
[1g] Mo Mu, MATH 3311: Introduction to Numerical Methods GD - Demostration Error in Lagrange Polynomials
[1h] Zhiliang Xu, ACMS 40390: Fall 2016 - Numerical Analysis GD
https://github.com/restrepo/Calculus/blob/master/Differential_Calculus.ipynb
Pretty print inside colaboratory
NumPy Polynomials
In Numpy there is an implementation of Polynomials. The object is initialized giving the polynomial coefficients:
More information about this
Copy an Paster in a MarkDown cell:
The numpy polynomial is automatically a function of its variable
By default, the assigned the attribute variable
is x
:
which can be assigned at initialization
Change of variable
Polynomial can be added but not multiplied, simplified or expanded
The object have in particular methods for
Integration:
Derivatives
roots:
=1.7763568394002505e-15
=1.7763568394002505e-15
It is possible to define polynomial by given the list of roots and
For further details check the official help:
Activity: Movement with uniform acceleration
Define a polynomial for the movement with uniform acceleration:
Use the previous formula expressed as polynomial of degree 2, to solve the following problem with
np.poly1d
:A car departs from rest with a constant acceleration of and travels through a flat and straight road. 10 seconds later a second pass for the same starting point and in the same direction with an initial speed of and a constant acelleration of . Find the time and distance at which the two cars meet.
Hint.
Sea el tiempo de encuentro definido que se interpreta como Puedo definir un nuevo polinomio Entonces , es la raíz del polinomio
La raíz 5 no es física porque el tiempo incial para el segundo carro es 10
meeting time 40 s; meeting point 4800 m
Linear Interpolation
When we have a set of discrete points of the form for , the most natural way to obtain (approximate) any intermediate value is assuming points connected by lines. Let's assume a set of points such that for an unknown function , if we want to approximate the value for , we construct an equation of a line passing through and .
The linear equation is
where
and is obtained by evaluating with either or
ParseError: KaTeX parse error: Expected & or \\ or \cr or \end at end of input: \begin{align} % f(x)\approx y = &\frac{y_{i+1}-y_i}{x_{i+1}-x_i}(x-x_i) + y_i \\ =&\frac{y_{i+1}-y_i}{x_{i+1}-x_i}x+\left[y_i-\frac{y_{i+1}-y_i}{x_{i+1}-x_i}x_i\right] \\ %ParseError: KaTeX parse error: Expected 'EOF', got '\end' at position 2: \̲e̲n̲d̲{align}and this can be applied for any such that and where it has been assumed an ordered set .
Steps LI
Once defined the mathematical basis behind linear interpolation, we proceed to establish the algorithmic steps for an implementation.
Establish the dataset you want to interpolate, i.e. you must provide a set of the form .
Give the value where you want to approximate the value .
Find the interval in which is embedded.
Use the above expression in order to find .
To make the linear interpolation we will use
The option kind
specifies the kind of interpolation:
'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic'
, where'zero', 'slinear', 'quadratic' and 'cubic'
refer to a spline interpolation of zeroth, first, second or third order)or as an integer specifying the order of the spline interpolator to use.
Default is 'linear'
correponding to integer 1.
Example 1
Sample the function between and using points (9 intervals). Plot both, the interpolation and the original function.
sp
reemplaza completamente a numpy con np
Interpolation with 9 equal intervals
Plotting the results adding the real function with enough points
Other kind
values: 0,1,2
We can see that the data poinst are just joined by straight lines:
However, the object f
behaves like a function. For example. We can evaluate both the real and the interpolated function in
Activity
Use the previous code and explore the behaviour of the Linear Interpolation algorithm when varying the number of data used.
Example:
Generate three points that do not lie upon a stright line, and try to make a manual interpolation with a polynomial of degree two.
Polynomial object in numpy
In numpy
it is possible to define polynomials friom either its coefficients o its roots with np.poly1d
Define a two degree polynomial from its roots:
We try to make a fit by using an inverted parabola passing trough the tree points and using the roots as a guess. In fact, we can try with a polynomial of degree two with roots at 1 and 22.
With we can flip the curve and reduce the maximum without change the roots
Activity: Scipy interpolation.
Define an interplation function which passes throgh the three points by using interp1D
of Scipy with several linear and quadratic curves between the points.
Lagrange Polynomial
Algebraic polynomials are very special functions as they have properties like differentiability (unlike linear interpolation) and continuity that make them useful for approximations like interpolation. A Polynomial is defined as a function given by the general expression:
where is the polynomial degree.
Another important property of polynomials is given by the Weierstrass Approximation Theorem, which states given a continuous function defined on a interval , for all , there exits a polynomial such that
This theorem guarantees the existence of such a polynomial, however it is necessary to propose a scheme to build it.
Derivation
Let's suppose a well-behaved yet unknown function and two points and for which and . With this information we can build a first-degree polynomial that passes through both points by using the last equation in sec. Linear Interpolation, we have
We can readily rewrite this expression like: In this way
where we define the functions and as:
Note that
implying:
Although all this procedure may seem unnecessary for a polynomial of degree 1, a generalization to polynomials of larger degrees is now possible.
General case
Let's assume again a well-behaved and unknown function sampled by using a set of data (). We call the set of as the node points of the interpolation polynomial in the Lagrange form, , where:
Such that
We need to find the Lagrange polynomials, , such that $$L_{n,i}(x_i) = 1\,,\qquad\text{and}\,,\qquad L_{n,i}(x_j) = 0\quad\text{for $i\neq jParseError: KaTeX parse error: Expected 'EOF', got '}' at position 1: }̲$ A function that satisfies this criterion is
Please note that in the expansion the term does not appears in both the numerator and the denominator as stablished in the productory condition .
Moreower and, for
Then, the polynomial of th-degree will satisfy the definitory property for a interpolating polynomial, i.e. for any and it is called the interpolation Polynomial in the Lagrange form.
Check this implementation in sympy [View in Colaboratory] where both the interpolating polynomial and the Lagrange polynomials are defined.
Further details at: Wikipedia
Example:
Obtain the Lagrange Polynomials for a Interpolation polynomial of degree 1.
, ,
Until now we can only guarantee that . To calculate the function from any in the interpolation interval we have the following Theorem (See here)
Theorem
Suppose are distinct numbers in the interval and .Then for each in , a number between , and hence in , exists with where the formula for the error bound is given by is the derivative of
For a demostration see [1d] → https://www.math.ust.hk/~mamu/courses/231/Slides/CH03_1B.pdf
The specific calculation of the bounded error is to find the and such that
Exercise-interpolation
Obtain the Lagrange Polynomials for a Interpolation polynomial of degree 2.
Implementation in Scipy
Example of error calculation
See details here
Consider interpolation in the interval
Construct the Lagrange Polynomial for the points , , .
Find the approximate value at and the error bound for the approximation
We start by defining the function
Be sure that the function input will be an array
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_1076705/3003427434.py in <module>
1 #List operations are not well defined in general
----> 2 [1,2,4]-[1,5,6]
TypeError: unsupported operand type(s) for -: 'list' and 'list'
The interpolation polynomial is
Test interpolation with one of the three points
For the bounded error we start with the left part where The maximum is obtained for the last point
For the right part we need just to build the numpy polynomial with roots at
And find the maximun of the absolute value of the critical points
The point in the interval for which is maximum corresponds to the root
Or
In this way, the maximum error for is expected for
The bounded error is then
The real bounded error is
Implementation in sympy
For details see here
Steps LP
Once defined the formal procedure for constructing a Lagrange Polynomial, we proceed to describe the explicit algorithm:
Give the working dataset and stablish how many points you have.
Define the functions in a general way.
Add each of those terms as shown in last expression.
Evaluate your result wherever you want.
Activity
Along with the professor, write an implementation of the previous algorithm during classtime.
Activity LP

One of the very first evidences of the existence of dark matter was the flat rotation curves of spiral galaxies. If we assume the total budget of mass of a galaxy is entirely made of luminous matter, the orbital circular velocity of stars around the galaxy plane should decay according to a keplerian potential. However this is not the case and the circular velocity barely decreases at larger radius, thus indicating the presence of a new non-visible matter component (dark matter). When it is necessary to determine how massive is the dark matter halo embedding a galaxy, an integration of the circular velocity is required. Nevertheless, due to the finite array of a CCD camera, only a discrete set of velocities can be measured and interpolation techniques are required.
In this activity we will take a discrete dataset of the circular velocity as a function of the radius for the galaxy NGC 7331 and perform both, a linear and a Lagrange interpolation. You can download the dataset from this link.
To which of two curves the real data approach better?
import os os.remove('trivia_results.txt')
{"name":"stdin","output_type":"stream","text":"A: to the curve \"velocity goes to zero when distance goes to infinity\"\nB: to the curve \"velocity goes to high constant when distance goes to infinity\"\n A\n"}
os.remove('trivia_results.txt')
Lets us check!
Build expected data
Logarithmic interpolation
Appendix
Thecnical details of interpolation functions: interpolation_details.ipynb
some blue text.
Hola