Least-squares line fitting: Difference between revisions
From JSXGraph Wiki
A WASSERMANN (talk | contribs) No edit summary |
A WASSERMANN (talk | contribs) No edit summary |
||
Line 15: | Line 15: | ||
for (i=0;i<5;i++) { | for (i=0;i<5;i++) { | ||
yr = 10*(Math.random()-0.5); | yr = 10*(Math.random()-0.5); | ||
xr = 0.*yr+delta*(Math.random()-0.5) | xr = 0.*yr+delta*(Math.random()-0.5); | ||
p.push(brd.create('point',[xr, yr], {withLabel:false})); | p.push(brd.create('point',[xr, yr], {withLabel:false})); | ||
} | } | ||
brd.unsuspendUpdate(); | brd.unsuspendUpdate(); | ||
var M = [], y = [], MT, B, c, z, n; | |||
n = p.length; | |||
for (i=0;i<n;i++) { | |||
M.push([p[i].X(), p[i].Y(), 1.0]); | |||
y.push(p[i].X()*p[i].X() + p[i].Y()*p[i].Y()); | |||
} | |||
// Now, the general linear least-square fitting problem | |||
// min_z || M*z - y||_2^2 | |||
// is solved by solving the system of linear equations | |||
// (M^T*M) * z = (M^T*y) | |||
// with Gauss elimination. | |||
MT = JXG.Math.transpose(M); | |||
B = JXG.Math.matMatMult(MT, M); | |||
c = JXG.Math.matVecMult(MT, y); | |||
z = JXG.Math.Numerics.Gauss(B, c); | |||
// Finally, we can read from the solution vector z the coordinates [xm, ym] of the center | |||
// and the radius r and draw the circle. | |||
var xm = z[0]*0.5; | |||
var ym = z[1]*0.5; | |||
var r = Math.sqrt(z[2]+xm*xm+ym*ym); | |||
brd.create('circle',[ [xm,ym], r]); | |||
/* | /* | ||
// Having constructed the points, we can fit a line described | // Having constructed the points, we can fit a line described |
Revision as of 11:16, 7 November 2010
This little JXSGraph application finds the line - described by homogeneous coordinates [a,b,c] - that minimizes
- [math]\displaystyle{ \sum_{i=1}^n (ax_i+by_i+cz_i)^2. }[/math]
Coming soon...