Skip to content

Instantly share code, notes, and snippets.

@jremmen
Created May 26, 2013 19:29
Show Gist options
  • Save jremmen/5653769 to your computer and use it in GitHub Desktop.
Save jremmen/5653769 to your computer and use it in GitHub Desktop.
js: programmatic
//fixed point example
var programmatic = {
tolerance: 0.0001,
isCloseEnough: function(x, y) {
return Math.abs((x - y) / x) / x < this.tolerance;
},
fixedPoint: function(f) {
return function(firstGuess) {
var iterate = function(guess) {
var next = f(guess);
if(programmatic.isCloseEnough(guess, next)) {
return next;
} else {
return iterate(next);
}
return next;
};
return iterate(firstGuess);
};
},
averageDamp: function(f) {
return function(x) {
return(x + f(x)) / 2;
};
}
};
// square root using fixed point 1
function sqrt(x) {
return programmatic.fixedPoint(function(y) { return (y + x / y) / 2; })(1.0);
}
// square root using fixed point and averageDamp
function sqrt2(x) {
return programmatic.fixedPoint(programmatic.averageDamp(function(y) { return x / y; }))(1.0);
}
// og loop average
function avg(nums) {
var t = 0;
for(i = 0; i < nums.length; i++) {
t += nums[i];
}
return t / nums.length;
}
// recursive average
function avg(nums) {
function sum(n) {
if(n && n.length > 0) {
return n[0] + sum(n.slice(1));
} else {
return 0;
}
}
return sum(nums) / nums.length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment