Skip to content

Instantly share code, notes, and snippets.

@sasekazu
Last active August 29, 2015 14:13
Show Gist options
  • Save sasekazu/4e73c6baa7e568f47a1b to your computer and use it in GitHub Desktop.
Save sasekazu/4e73c6baa7e568f47a1b to your computer and use it in GitHub Desktop.
最小二乗法によるn次多項式の当てはめ least square
// numeric.jsを使用
// データ点を配列で渡す 例: points = [[x0,y0],[x1,y1],[x2,y2],[x3,y3]];
// 多項式の係数を配列で返す
// dim=2 -> 直線
// dim=3 -> 二次曲線
function leastSquareN(points, dim) {
if(points.length<dim) {
return numeric.rep([dim], 0);
}
var A=numeric.rep([dim, dim], 0);
var b=numeric.rep([dim], 0);
for(var i=0; i<points.length; ++i) {
for(var j=0; j<dim; ++j) {
for(var k=0; k<dim; ++k) {
A[j][k]+=Math.pow(points[i][0], 2*(dim-1)-j-k);
}
}
for(var j=0; j<dim; ++j) {
b[j]+=points[i][1]*Math.pow(points[i][0], dim-1-j);;
}
}
var c=numeric.solve(A, b)
return c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment