Created
January 25, 2018 07:20
-
-
Save jianminchen/8068e85f3e0a0e2b6cad4826ae6a8866 to your computer and use it in GitHub Desktop.
Root of a number - binary search - peer wrote JavaScript code
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
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