Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var x = [1, 2, 3, 4, 5];
- var y = x.map(function(x) { return 2.1*x + 0.2; });
- //Don't feel like including underscore
- function zip(a) {
- var ordered = a[0].length <= a[1].length;
- var x = ordered ? a[0] : a[1];
- var y = ordered ? a[1] : a[0];
- return x.map(function (x, i) {
- return ordered ? [ x, y[i] ]
- : [ y[i], x ];
- });
- }
- function sum(x) {
- var accum = 0;
- x.forEach(function(y) { accum+=y; });
- return y;
- }
- //Not what I want to do.
- function ssd(xvals, yvals) {
- var set = zip(xvals, yvals);
- return sum( set.map(function (tuple) {
- return Math.pow(tuple[0] - tuple[1], 2);
- }));
- }
- function initialGuess(x, y) {
- var set = zip([x, y]);
- var a = set[0];
- var b = set[set.length-1];
- var m = (b[1] - a[1]) / (b[0] - a[0]);
- var intercept = a[1] - m*a[0];
- return [m, intercept];
- }
- //broked, needs to be 2d
- //I think, for this case, using steepest descent would be more than reasonable.
- function newtonIteration (fxn, xi) {
- var dx = 0.01;
- return xi - fxn(xi)/derivative(fxn, xi, dx);
- }
- function derivative(fxn, x, dx) {
- return ( fxn(x+dx/2) - fxn(x-dx/2) ) / dx;
- }
- function iterate(iterfxn, stopfxn, x0) {
- var xold = x0;
- var xnew = x0;
- var xtemp = x0;
- do {
- console.log(xold);
- console.log(xnew);
- xtemp = xnew;
- xnew = iterfxn(xold);
- xold = xtemp;
- console.log(xold);
- console.log(xnew);
- } while (!stopfxn(xnew, xold));
- return xnew;
- }
- function line(consts) {
- return function(x) {
- return consts[0]*x + consts[1];
- }
- }
- function objectiveFxn(consts) {
- return ssd( x.map(line(consts)), yvals );
- }
- var result = iterate( function(C) { return newtonIteration(objectiveFxn); },
- function(xnew, xold) { return abs(objectiveFxn(xnew)
- - objectiveFxn(xold)) < 0.001; },
- initialGuess(x, y) );
- console.log(result[0] + 'x' + result[1]);
Add Comment
Please, Sign In to add comment