mirror of
https://github.com/ossu/computer-science.git
synced 2025-01-15 01:07:19 -05:00
Find closest number to be a square root of another number - bisection method
This commit is contained in:
parent
2956d63a86
commit
0802268ed7
@ -69,23 +69,52 @@ var prompt = require( 'prompt' );
|
|||||||
|
|
||||||
// });
|
// });
|
||||||
|
|
||||||
// Find closest number to be a square root of another number
|
// // Find closest number to be a square root of another number - Brute Force
|
||||||
var x = 25;
|
// 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 epsilon = 0.01;
|
||||||
var numGuesses = 0;
|
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 ) {
|
while ( Math.abs( Math.pow( ans, 2 ) - x ) >= epsilon && ans <= x ) {
|
||||||
|
|
||||||
ans += 0.00001;
|
|
||||||
numGuesses += 1;
|
numGuesses += 1;
|
||||||
|
|
||||||
|
if ( Math.pow( ans, 2 ) < x ) {
|
||||||
|
|
||||||
|
low = ans;
|
||||||
|
|
||||||
|
} else {
|
||||||
|
|
||||||
|
high = ans;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
ans = ( high + low ) / 2;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log( 'numGuesses: ' + numGuesses );
|
console.log( 'numGuesses:', numGuesses );
|
||||||
|
console.log( ans, 'is close to square root of', x );
|
||||||
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());
|
|
||||||
}
|
|
Loading…
Reference in New Issue
Block a user