Binary search - precision issues - not sure how to proceed

Back to General discussions forum

bmarkey     2015-11-12 18:25:25

I'm stuck on binary search. It's a precision thing. I've tried SO and I've tried reddit and no answer.

Here is your answer:

72.4134839547 68.0596882911 90.6965170455 81.0350608202 35.6846548341 82.8909638421

Here are my answers:

Without decimal format:

72.41478544213217 68.06710831781339 90.70095754595462 81.0511807170825 35.70315377882463 83.0481061013177

With decimal format:

72.4147854421 68.0671083178 90.700957546 81.0511807171 35.7031537788 83.0481061013

I've searched the forums, saw about making sure to use double etc. I'm not really sure how to proceed here.

Can you point me in the right direction? I've tried multiple data sets, and I fail them all.

Rodion (admin)     2015-11-12 18:56:28
User avatar

Hi! thanks for your message!

I took a look at your solution and these lines seem strange to me:

if ((int) result > 0) {
    upperBound = mid;
} else if ((int) result < 0) {
    lowerBound = mid;
} else if((int) result == 0){

Why do you convert result to (int) before comparison?

I believe that for result = 0.9 for example (int) result is 0 - so you have an unwanted loss of accuracy...

I'm not sure it is the cause of the trouble, but probably it is worth trying to start from here...

bmarkey     2015-11-12 19:02:33

I'm doing that because it will never actually equal 0. That is ONLY for comparison, all match is still double. Without that result approaches 0... something like 4.983423423423432E-7 or something of that nature.

There should be no loss of precision since im setting upperBound and lowerBound from mid, which is still double.

Rodion (admin)     2015-11-12 19:11:45
User avatar

> I'm doing that because it will never actually equal 0

But in this way you treat any result between 0.0 and 1.0 as 0 and stop the calculation too early, when result is really very far from 0.0... :)

Normally we compare doubles with zero in a way like this:

double eps = 1e-10; // e.g. very small value, like 0.0000000001
double result = ... ;
if (Math.abs(result) < eps) { // e.g. -eps < result && result < eps
    // than we think of it as zero
}

Hope this may help!

bmarkey     2015-11-12 19:13:05

Oh well. Then I learned something today, thank you! Let me try that.

bmarkey     2015-11-12 19:40:01

That was it! Thank you again.

Please login and solve 5 problems to be able to post at forum