Skip to content
Python for Quantitative Finance / Control Flow and Simple Numerical Programs

Bisection Search and the Perils of Floats

Exhaustive Enumeration and Approximate Solutions ended on a cost problem: marching through a grid one step at a time costs O(range/step)O(\text{range}/\text{step}) guesses, and tightening the tolerance ϵ\epsilon multiplies that cost. Bisection search fixes this by discarding half the remaining search space on every guess instead of one grid point — a change that turns a cost linear in 1/ϵ1/\epsilon into one that is only logarithmic in 1/ϵ1/\epsilon. This is the first genuinely fast algorithm in the vault, and it is also the first place a subtlety of float arithmetic bites: comparing floats for exact equality is unreliable, and every bisection search must be written around a tolerance, never around ==. This note builds bisection for approximate square roots, proves why it is dramatically faster than enumeration, and then details exactly how and why floating-point numbers fail to represent most real numbers exactly.
Learning objectives. By the end of this note you should be able to:
  • implement bisection search for an approximate square root, tracking the search interval [low,high][\text{low}, \text{high}] across iterations;
  • explain, using the halving argument, why bisection search needs on the order of log⁡2(range/ϵ)\log_2(\text{range}/\epsilon) guesses rather than range/ϵ\text{range}/\epsilon;
  • state why float values should never be compared with ==, and what to compare instead;
  • describe, at a working level, why floats are stored in binary and why this makes exact decimal fractions like 0.10.1 unrepresentable.

In this lesson

  1. Bisection search for an approximate square root
  2. The peril of comparing floats with ==

Before you start

The full lesson, with worked examples and exercise solutions, is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.