awelgorithms

Binary search a real interval

Updated

On reals you search a continuous interval [lo, hi], not indices. mid = (lo + hi) / 2, and the predicate is about f(mid), here mid * mid ≤ n.

What to focus on

There is no next-integer step. Move lo or hi to mid and stop when hi − lo is below the tolerance. The answer is within 1e-4 of the true root.

Worked examples

perfect square

n = 9
  1. [0, 9] halves toward 3

Result: 3

irrational

n = 2
  1. [0, 2] halves toward 1.4142

Result: 1.4142

larger square

n = 16
  1. [0, 16] halves toward 4

Result: 4

Try it

Write realSqrt(n). n is a positive real number. Binary search the real interval [0, max(1, n)] until its width is below 1e-4 and return the midpoint, rounded to 4 decimal places. On 9 return 3. On 2 return 1.4142. On 16 return 4.

n is a positive real. mid * mid is monotone on the interval.