Problem solving · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Floating-Point Equality

easydebugging

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_total

Symptom: 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 → expected True. Actual False: 0.1 + 0.2 evaluates to 0.30000000000000004.
  • line_items = [(3, 0.10)], declared_total = 0.30 → expected True. Actual False: 3 * 0.1 is 0.30000000000000004 as well.
  • line_items = [(2, 0.25), (1, 0.50)], declared_total = 1.00 → True in both versions. 0.25 and 0.5 are exact binary fractions, so this merchant is never flagged, which is why the failures looked random.

Hints

  1. Print computed and declared_total with repr() (or f"{x:.20f}") on a flagged invoice instead of with the default two-decimal formatting.
  2. Which decimal fractions can be written exactly as a sum of powers of two? 0.5 can. Can 0.1?
  3. 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