Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 25, 2018 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/8068e85f3e0a0e2b6cad4826ae6a8866 to your computer and use it in GitHub Desktop.
Save jianminchen/8068e85f3e0a0e2b6cad4826ae6a8866 to your computer and use it in GitHub Desktop.
Root of a number - binary search - peer wrote JavaScript code
function root(x, n) {
let marginError = 0.001;
let guess; // upper bound
if(x===1){
return 1;
}
if(x>1){
guess = x;
}
if(x<1){
guess = 1;
}
let increment = x/2;
return tryRoot({x,n,marginError,guess, increment});
}
function tryRoot({x,n,marginError,guess, increment}){
let cur = 1;
//calculate guess ^ n
for(let i=0;i<n;i++){
cur *= guess;
}
if(x - cur > marginError){
//increase guess
let newGuess = guess + increment;
//retry
return tryRoot({x,n,marginError,guess:newGuess,increment:increment/2});
}else if(x - cur < -1 * marginError){
//lower guess
let newGuess = guess - increment;
//retry
return tryRoot({x,n,marginError,guess: newGuess,increment:increment/2});
}else{
//return guess
return Math.round(guess*1000)/1000;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment