Least-squares line fitting: Difference between revisions

From JSXGraph Wiki
No edit summary
No edit summary
Line 9: Line 9:
brd.suspendUpdate();
brd.suspendUpdate();
for (i=0;i<100;i++) {
for (i=0;i<100;i++) {
   yr = 10*(Math.random()-0.5);
   xr = 10*(Math.random()-0.5);
   xr = 0*yr+delta*(Math.random()-0.5) +1.0;
   yr = 0.3*xr+delta*(Math.random()-0.5) +1.0;
   p.push(brd.create('point',[xr, yr], {withLabel:false}));
   p.push(brd.create('point',[xr, yr], {withLabel:false}));
}
}
brd.unsuspendUpdate();
brd.unsuspendUpdate();


// Having constructed the points, we can fit a circle
// Having constructed the points, we can fit a line described
// by homogeneous coordinates
// through the point set, consisting of n points.
// through the point set, consisting of n points.
// The (n times 3) matrix consists of
// The (n times 2) matrix consists of
//  1, x_1, y_1
//  x_1, y_1
//  1, x_2, y_2
//  x_2, y_2
//      ...
//      ...
//  1, x_n, y_n
//  x_n, y_n
// where x_i, y_i is the position of point p_i
// where x_i, y_i is the position of point p_i
// y is equal to the zero vector.
// y is equal to the all-minus-one vector.
var M = [], y= [], MT, B, c, z, n;
var M = [], y= [], MT, B, c, z, n;
n = p.length;
n = p.length;
Line 40: Line 41:
c = JXG.Math.matVecMult(MT, y);
c = JXG.Math.matVecMult(MT, y);
z = JXG.Math.Numerics.Gauss(B, c);
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('line',[1, z[0], z[1]]);  
brd.create('line',[1, z[0], z[1]]);  

Revision as of 19:35, 5 November 2010