Here is a polynomial interpolator implemented as a C++ header file: interpolator.hpp
I recently learned this method of creating a generic polynomial
The idea behind the algorithm is so simple and intuitive that I thought it would be fun to implement and share.
This code allows a caller to specify the data types
used for domain_t
) and range_t
). For example, if you want,
double
and std::complex<double>
.
Or both could be float
.
I will start with an easy but non-trivial example. Suppose we have three points on the Cartesian plane:
1 | 7 |
2 | -2 |
3 | 6 |
We want to find the formula for a quadratic polynomial that generates these values. When plotted, this function will result in a parabola that passes through the points.
To solve this problem, imagine that we can express
All I've done here is use each of the desired
The simple idea is, when
Likewise, when
Completing the pattern, we also need
How do we find the functions
Let's start with
However, there is a problem. If we evaluate
We need the value to be 1, not 2, so the fix is to divide by 2 in the definition of
And that's it! The remaining functions follow the same line of thinking. This results in the desired polynomial solution:
With a little algebra, the binomials can be expanded, terms can be collected and simplified, and the result is a tidy quadratic polynomial:
A little sanity check in Python confirms we didn't make any mistakes:
>>> def f(x):
... return (17/2)*x*x - (69/2)*x + 33
...
>>> f(1)
7.0
>>> f(2)
-2.0
>>> f(3)
6.0
The same approach generalizes to any number of points
Written in a general form, the polynomial curve passing through
Note that the fraction after each
Written more compactly, the formula is
The above formula is compact and easy to understand, but it's not the most
efficient way to evaluate
The C++ code in this project does exactly that. It consists of a class template
called Interpolator
. After creating an instance of Interpolator
, you can call
its insert
method to insert as many points
Then call its polynomial
method to return an object of type Polynomial
.
The Polynomial
class represents a polynomial in terms of a single independent
variable
Is represented by the list [-11, 7, -4, 17]
. Note that the coefficients go
from lowest order
The Polynomial
instance overloads the parentheses operator ()
to allow
treating it syntactically like a function of
There are some handy overloaded operators in Polynomial
for multiplying, adding,
and subtracting polynomials with scalar constants or other polynomials.
Also are included are calculus methods: you can take the derivative or
the integral of a polynomial with respect to its indepdendent variable x
.
Here is a sample C++ program that finds the cubic function passing through four points. Once found, the program prints the polynomial and evaluates it at a few points.
Here is the output from the demo program.