Page 1 of 1
Looking for Cubic Spline Interpolation Code
Posted: Tue Jul 13, 2010 12:36 am
by ExpertAlmost
Good morning!
I have a set of discrete data points from which I need to interpolate new values. My (neophyte) mathematical research suggests that cubic spline interpolation gives the best result with the least amount of calculation overhead.
I expected to find any number of functions in PHP (input two x,y points, and a point to interpolate: output the interpolated point) but cannot find any. I find C/C++ code, Matlab, even VBA. I could probably port some of that code over, but can anyone point me to so tested-ready-to-run code?
Thanks!
Re: Looking for Cubic Spline Interpolation Code
Posted: Tue Jul 13, 2010 1:15 am
by Apollo
For cubic interpolation, you'd need 4 input points, or 2 input points + their slopes. With just 2 input points, the best you can do is linear interpolation:
Code: Select all
<?php
class Point
{
var $x, $y;
function __construct( $x, $y ) { $this->x = $x; $this->y = $y; }
};
function BilinearInterpolate( $x, $a, $b ) // $a and $b are two points, to be interpolated at position $x
{
$s = ($b->y - $a->y) / ($b->x - $a->x);
return $a->y + $s * ($x - $a->x);
}
$p = new Point(3,1);
$q = new Point(8,4);
$x = 5;
$y = BilinearInterpolate($x,$p,$q);
print("$x , $y"); // outputs 5 , 2.2
?>
There are different interpretations and solutions for cubic interpolation, meeting different conditions (such as hitting all 4 points, or assuming the natural slope between them, or enforce a smooth curve if you concatenate multiple piecewise cubic curves, etc). It also makes a difference whether the input points are distributed evenly (having the same difference between subsequent x's) or randomly.
Re: Looking for Cubic Spline Interpolation Code
Posted: Tue Jul 13, 2010 1:30 am
by ExpertAlmost
Thank you Apollo!
Apparently there is more to it than I orginally thought. That's never happened before...

The interpolation does have to hit all the points.
Actually, I have a set of 50 data points, with many of the point clustered. This is not for a graphics application, but for a statistical one.
What I eventually need to do is find the points that approximate 5%, 80% and 95% areas under the curve described by those points. Rarely (eg. randomly) will my actual data points hit those values. Similar to an approximation done under a bell curve but I do not have the luxury of that simplicity. Once I figure out how to do the cubic spline interpolation, I was going to use a simple trapazoidal method. Another piece of PHP code I hope to find
Of course if I found a piece of code that gave me the solutions for 5%, 80% and 95% areas under a curve given a set of data points.....well....I could....take a nap
Any ideas? (for the math or code--naps I can manage)