Created
February 4, 2020 08:40
-
-
Save wmjd/9315d84a52aba02b7121e803fdd9de56 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Heron's method | |
function sqrt(n){ | |
var close_enuf = 0.001 | |
function iterate(guess){ | |
console.log(guess); | |
var next = (guess + n/guess)/2; | |
return (Math.abs(guess-next) < close_enuf) ? next : iterate(next); | |
} | |
iterate(Math.random()*n); | |
} | |
// My variation | |
function sqrt(n){ | |
let close_enuf = 0.001 | |
function iterate(guess){ | |
console.log(guess); | |
let factor = n/guess; | |
let diff = Math.abs(guess - factor); | |
let min = (factor > guess) ? guess : factor; | |
let next = min + diff*Math.random(); | |
return (Math.abs(guess-next) < close_enuf) ? next : iterate(next); | |
} | |
iterate(Math.random()*n); | |
} | |
//Fixed_point translated from SICP | |
function fixed_point(f, first_guess){ | |
let tolerance = 0.001 | |
function is_close_enuf(a, b){ | |
return (tolerance > Math.abs(a-b)); | |
} | |
function try_the(guess){ | |
let next = f(guess); | |
if(is_close_enuf(guess,next)) | |
return next; | |
else | |
return try_the(next); | |
} | |
return try_the(first_guess); | |
} | |
// Could use fixed_point by calling fixed_point(Math.cos, Math.random()); | |
// Can also use it for Heron's method with the appropriate argument | |
// This function does that: | |
function generate(n){ | |
function heron(x){ | |
return (x+n/x)/2; | |
} | |
return heron; | |
} | |
// Find the square root of 4 by calling fixed_point(generate(4), Math.random()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment