I would like to compute the coefficients a0
, a1
, and a2
of a quadradic function (polynomial of degree 2) given three points (x0, y0)
, (x1, y1)
, and (x2, y2)
, where yi = a0 + a1*xi + a2*xi*xi
?
I have tried the following two formulas, but I am not really impressed with the precision of the output
final double x0mx1, x0mx2, x1mx2, t0, t1, t2;
double a2, a1, a0;
x0mx1 = (x0 - x1);
x0mx2 = (x0 - x2);
x1mx2 = (x1 - x2);
// method one
t0 = (y0 / (x0mx1 * x0mx2));
t1 = (y1 / (-x0mx1 * x1mx2));
t2 = (y2 / (x0mx2 * x1mx2));
a2 = (t0 + t1 + t2);
a1 = -((t0 * (x1 + x2)) + (t1 * (x0 + x2)) + (t2 * (x0 + x1)));
a0 = (t0 * x1 * x2) + (t1 * x0 * x2) + (t2 * x0 * x1);
// method two
a2 = ((((y1 - y0) * (x0mx2)) + ((y2 - y0) * ((-x0mx1)))) /
(((x0mx2) * ((x1 * x1) - (x0 * x0)))
+ (((-x0mx1)) * ((x2 * x2) - (x0 * x0)))));
a1 = (((y1 - y0) - (a2 * ((x1 * x1) - (x0 * x0)))) / ((-x0mx1)));
a0 = y0 - (a2 * x0 * x0) - (a1 * x0);
The results do sort of fit, i.e., seem roughly to be within a +/- 1e-5 * max{ |a0'|, |a1'|, |a2'| }
window of the real solution a0'
, a1'
, and a2'
.
Is there a better, more numerically stable way to compute the coefficients?
I am using Java, btw, although I think this does not matter.
Cheers, Thomas.