From 0802268ed7ee0a54488515208b60382c73db7237 Mon Sep 17 00:00:00 2001 From: ericdouglas Date: Wed, 3 Jun 2015 12:04:42 -0300 Subject: [PATCH] Find closest number to be a square root of another number - bisection method --- .../src/03-lecture.js | 51 +++++++++++++++---- 1 file changed, 40 insertions(+), 11 deletions(-) diff --git a/computer-science/01-introduction-to-cs-and-programming-mit/src/03-lecture.js b/computer-science/01-introduction-to-cs-and-programming-mit/src/03-lecture.js index b0b4d83..2783dd5 100644 --- a/computer-science/01-introduction-to-cs-and-programming-mit/src/03-lecture.js +++ b/computer-science/01-introduction-to-cs-and-programming-mit/src/03-lecture.js @@ -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()); -} \ No newline at end of file +console.log( 'numGuesses:', numGuesses ); +console.log( ans, 'is close to square root of', x ); \ No newline at end of file