Floating-Point Equality
Problem
An invoicing service checks that the line items on an invoice add up to the total the merchant declared, and flags anything that does not match for manual review:
def totals_match(line_items: list[tuple[int, float]], declared_total: float) -> bool:
"""line_items are (quantity, unit_price) pairs."""
computed = 0.0
for qty, unit_price in line_items:
computed += qty * unit_price
return computed == declared_totalSymptom: a few percent of invoices are flagged as mismatched, but when a reviewer opens them the line items and the total agree to the cent. The flagged invoices have nothing obviously in common; the same merchant is sometimes flagged and sometimes not. Explain the false positives and fix the function so the review queue only contains real mismatches.
Examples
line_items = [(1, 0.10), (1, 0.20)], declared_total = 0.30→ expectedTrue. ActualFalse:0.1 + 0.2evaluates to0.30000000000000004.line_items = [(3, 0.10)], declared_total = 0.30→ expectedTrue. ActualFalse:3 * 0.1is0.30000000000000004as well.line_items = [(2, 0.25), (1, 0.50)], declared_total = 1.00→Truein both versions.0.25and0.5are exact binary fractions, so this merchant is never flagged, which is why the failures looked random.
Hints
- Print
computedanddeclared_totalwithrepr()(orf"{x:.20f}") on a flagged invoice instead of with the default two-decimal formatting. - Which decimal fractions can be written exactly as a sum of powers of two?
0.5can. Can0.1? - Money has a natural smallest unit. What happens if you count in that unit instead of in floating-point dollars?
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.