Find closest number to be a square root of another number - bisection method

This commit is contained in:
ericdouglas 2015-06-03 12:04:42 -03:00
parent 2956d63a86
commit 0802268ed7

View File

@ -69,23 +69,52 @@ var prompt = require( 'prompt' );
// });
// Find closest number to be a square root of another number
var x = 25;
// // Find closest number to be a square root of another number - Brute Force
// var x = 25;
// var epsilon = 0.01;
// var numGuesses = 0;
// var ans = 0;
// while ( Math.abs( Math.pow( ans, 2 ) - x ) >= epsilon && ans <= x ) {
// ans += 0.00001;
// numGuesses += 1;
// }
// console.log( 'numGuesses: ' + numGuesses );
// if ( Math.abs( Math.pow( ans, 2 ) - x >= epsilon )) {
// console.log( 'Failed on square root of ' + x.toString());
// } else {
// console.log( ans.toString() + ' is close to square root of ' + x.toString());
// }
// Find closest number to be a square root of another number - bisection method
var x = 12345;
var epsilon = 0.01;
var numGuesses = 0;
var ans = 0;
var low = 0;
var high = x;
var ans = ( high + low ) / 2;
while ( Math.abs( Math.pow( ans, 2 ) - x ) >= epsilon && ans <= x ) {
ans += 0.00001;
numGuesses += 1;
if ( Math.pow( ans, 2 ) < x ) {
low = ans;
} else {
high = ans;
}
ans = ( high + low ) / 2;
}
console.log( 'numGuesses: ' + numGuesses );
if ( Math.abs( Math.pow( ans, 2 ) - x >= epsilon )) {
console.log( 'Failed on square root of ' + x.toString());
} else {
console.log( ans.toString() + ' is close to square root of ' + x.toString());
}
console.log( 'numGuesses:', numGuesses );
console.log( ans, 'is close to square root of', x );