I'm trying to find a number between min
and max
. I only know (through using the more
method) whether the number I'm guessing is higher or lower than the number passed. The number that I need to find can be a decimal, which is what is making me nervous, as the average binary search seems to mostly concern itself with the business of integers.
The algorithm I've written is an attempt at a binary search, without the array. The difference, as I see it, between a classical binary search is that the values and the index of the search have been conflated into the same task.
var tolerance = 0;
var tries, min, max, current, needed;
function search () {
tries = 0;
min = 0;
max = 100;
needed = Math.random() * max;
current = (max - min) / 2;
while (!accept() && tries < 100) {
if (more(current))
min = current;
else
max = current;
current = min + ((max - min) / 2);
tries++;
}
results();
}
function more (n) {
return n < needed;
}
function accept () {
return Math.abs(current-needed) <= tolerance;
}
function results () {
document.getElementById('results').innerHTML = 'accepted: ' + current + '<br>needed: ' + needed + '<br>tries: ' + tries;
}
<button onclick="javascript:search();">search</button>
<br>
<div id="results"></div>
My question is this; given what I want to do, can this code be improved upon? Or perhaps there is a better way of doing this all together? Obviously, the number of tries is greatly improved by increasing the tolerance - but it's at the expense of the accuracy of the final result. For example, would it make sense for me to increase the tolerance after a certain number of tries?
Also, how best would one go about ensuring that the needed number is in range? I know I could ensure that !more(max) && more(min)
before attempting the while
loop, but is there a more efficient way than simply bolting on two extra checks at the beginning of the script?