from numpy import *
from scipy import linalg
from scipy.linalg import norm
from matplotlib.pyplot import *
from prettytable import PrettyTable
from timeit import default_timer as timer
import sys
sys.path.append('fncbook/')
import fncbook as FNC
# This (optional) block is for improving the display of plots.
# from IPython.display import set_matplotlib_formats
# set_matplotlib_formats("svg","pdf")
# %config InlineBackend.figure_format = 'svg'
rcParams["figure.figsize"] = [7, 4]
rcParams["lines.linewidth"] = 2
rcParams["lines.markersize"] = 4
rcParams['animation.html'] = "jshtml" # or try "html5"
The Lagrange formula (9.1.4) is useful theoretically but not ideal for computation. For each new value of x, all the cardinal functions ℓk must be evaluated at x, which requires a product of n terms. Thus, the total work is O(n2) for every value of x. Moreover, the formula is numerically unstable. An alternative version of the formula improves on both issues.
as well as a set of values derived from the nodes.
The following formula is the key to efficient and stable evaluation of a polynomial interpolant.
Equation (9.2.3) is certainly an odd-looking way to write a polynomial! Indeed, it is technically undefined when x equals one of the nodes, but in fact, limx→tkp(x)=yk, so a continuous extension to the nodes is justified. (See Exercise 9.2.3.)
For certain important node distributions, simple formulas for the weights wk are known. Otherwise, the first task of an implementation is to compute the weights wk, or more conveniently, wk−1.
We begin with the singleton node set {t0}, for which one gets the single weight w0=1. The idea is to grow this singleton into the set of all nodes through a recursive formula. Define ωk,m−1 (for k<m) as the inverse of the weight for node k using the set {t0,…,tm−1}. Then
A direct application of (9.2.2) can be used to find ωm,m. This process is iterated over m=1,…,n to find wk=ωk,n−1.
In Function 9.2.1 we give an implementation of the barycentric formula for polynomial interpolation.
Computing all n+1 weights in Function 9.2.1 takes O(n2) operations. Fortunately, the weights depend only on the nodes, not the data, and once they are known, computing p(x) at a particular value of x takes just O(n) operations.
You might suspect that as the evaluation point x approaches a node tk, subtractive cancellation error will creep into the barycentric formula because of the term 1/(x−tk). While such errors do occur, they turn out not to cause trouble, because the same cancellation happens in the numerator and denominator. In fact, the stability of the barycentric formula has been proved, though we do not give the details.