Mathematics Book 1 Companion: Arithmetic and NumbersMaths Book 1 · Companion
0 / 0

Workbench / Mathematics Book 1 Companion: Arithmetic and Numbers

B1·08

Ratio, Proportion and Rates

Around chapter 8: how ratios, proportion and rates connect fractions to prices, speeds, scaling and fair comparisons; three other ways to see them; what the chapter simplifies (testing proportion with floats, scaling to whole pixels, rates that can't be combined at all); how Python's statistics.harmonic_mean averages rates with weights; four debugging drills; and interview questions.

6 topics · ~13 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Ratio a:b ("for every a, b") → equivalent ratios, simplest form by the gcd (chapter 5) → part to whole aa+b (chapter 6).
  • Sharing in a ratio: count parts → one part → multiply → round with a rule that keeps the total (chapter 6's exercises, S3).
  • Proportion ab=cd → cross-products (chapter 6) → rule of three ≡ unit method (unit rate).
  • Direct (y=kx, constant ratio) / inverse (xy=k, constant product) / linear with a fixed part / none: test, don't assume.
  • Scaling: lengths × k, areas × k2, volumes × k3 (chapter 10's powers).
  • Rates (different units: ₹/kg, km/h) → unit prices → combine by totals (the mediant) → average speed = harmonic mean for equal distances → Simpson's paradox when groups are split differently → standardise to a common mix.
  • Next: negative numbers (chapter 9), powers and scaling laws (chapter 10), units and dimensional analysis (chapter 11).

Explain it differently

A ratio is a recipe card, an amount is a pot. The card says 2 rice : 3 water; the pot says how much you're making. Scaling changes the pot, never the card. Every ratio problem is either "here's the card and the pot size, fill the pot" (sharing) or "here's one ingredient's amount, how big is the pot?" (the rule of three).

A rate is an exchange counter. ₹65 per kg is a counter where 1 kg is exchanged for ₹65. Two counters can be chained (₹ per kg × kg per bag = ₹ per bag) and turned around (kg per ₹), but two different counters' rates can't be averaged into one; you have to add up what actually crossed each counter.

Simpson's paradox is comparing two teams' batting averages when one team only played on difficult pitches. Each batter on team A outscores the matching batter on team B pitch by pitch, but team A's season average is lower because it played most of its games on the hard pitches. Compare on the same pitches, or weight both by the same schedule.

Gaps and misconceptions

What the chapter oversimplifies

1. "Direct proportion means the ratio is constant", which floats can't test exactly. The chapter's test compares ratios for equality. With decimals stored as floats, equal ratios can come out unequal:

Python
from fractions import Fraction as F
xs, ys = [1, 2, 3, 7], [0.1, 0.2, 0.3, 0.7]
print("float ratios:", [y / x for x, y in zip(xs, ys)])
print("distinct float ratios:", len({y / x for x, y in zip(xs, ys)}),
      "| distinct exact ratios:", len({F(str(y)) / x for x, y in zip(xs, ys)}))
Text
float ratios: [0.1, 0.1, 0.09999999999999999, 0.09999999999999999]
distinct float ratios: 2 | distinct exact ratios: 1

0.3÷3 is not exactly 0.1 in binary, so a naive check calls a perfectly proportional table "not proportional". Use exact fractions from decimal strings (as the exercises' P3 does), or compare with a tolerance suited to measured data, where small deviations are noise anyway.

2. "Scaling keeps the ratio", which whole units can't always do. Recipes scale smoothly; screens, prints and pixels come in whole units, so a scaled size must be rounded and the ratio drifts:

Python
from fractions import Fraction as F
w, h = 1920, 1080
for new_w in (1000, 640, 300, 333):
    new_h = round(h * new_w / w)
    print(f"{new_w} x {new_h}: ratio {F(new_w, new_h)} = {new_w / new_h:.5f} (16:9 = {16 / 9:.5f})")
Text
1000 x 562: ratio 500/281 = 1.77936 (16:9 = 1.77778)
640 x 360: ratio 16/9 = 1.77778 (16:9 = 1.77778)
300 x 169: ratio 300/169 = 1.77515 (16:9 = 1.77778)
333 x 187: ratio 333/187 = 1.78075 (16:9 = 1.77778)

A 16 : 9 image resized to 640 wide stays exactly 16 : 9 (360 is a whole number), but at 1,000, 300 or 333 wide the height must be rounded and the ratio is off by up to about 0.2 %. Only widths that are multiples of 16 keep it exactly. Small drifts are invisible; repeated rescaling, or computing one dimension from an already-rounded other, compounds them. Drill D1 is the version that isn't small.

3. "Rates combine by totals", which needs totals that add. Counts, distances and times add, so rates built from them combine. Some summary numbers have no totals to add, and can't be combined at all:

Python
import random
random.seed(8)
def p95(xs):
    xs = sorted(xs); return xs[int(0.95 * (len(xs) - 1))]
fast = [random.expovariate(1 / 40) for _ in range(9_000)]       # ms, a busy healthy shard
slow = [random.expovariate(1 / 200) for _ in range(1_000)]      # a small struggling shard
print(f"p95 fast {p95(fast):.0f} ms, slow {p95(slow):.0f} ms")
print(f"average of the p95s {(p95(fast) + p95(slow)) / 2:.0f} ms | true p95 of all requests {p95(fast + slow):.0f} ms")
Text
p95 fast 120 ms, slow 589 ms
average of the p95s 355 ms | true p95 of all requests 181 ms

The 95th percentile of response time (95 % of requests are faster) is 120 ms on a busy healthy shard and 589 ms on a small struggling one. Their average, 355 ms, means nothing; the true 95th percentile of all requests is 181 ms, and no formula gets it from the two percentiles. You need the underlying data or a mergeable summary (a histogram with shared buckets). Averages and rates are mergeable from counts; percentiles, medians and maxima of rates aren't.

Common misconceptions

Misconception What's actually true Where it's shown
"A table with equal ratios will pass len(set(y / x)) == 1." Float rounding can split equal ratios; use exact fractions or a tolerance. What the chapter oversimplifies, point 1
"Resizing keeps the aspect ratio." Rounding to whole pixels makes it drift, except at exact multiples. What the chapter oversimplifies, point 2
"Any summary of a rate can be combined across groups." Totals combine; percentiles and medians don't. What the chapter oversimplifies, point 3
"Compute the scale factor first, in integers." new_w // w is 0 when shrinking; multiply first, then divide. Drill D1
"The rule of three always multiplies by the new amount." For inverse proportion it divides: more workers, fewer days. Drill D2
"Converting decimals to integers with int(x * 100) is safe." Floats just below the value truncate down: 0.29 m becomes 28 cm. Drill D3
"A rate rounded to two places is good enough." Its error is multiplied by every amount converted, and inverting it rounds again. Drill D4

Theoretical gaps: the ideas behind the chapter

  • Proportion is linearity through the origin. y=kx is the simplest linear function; "linear with a fixed part", y=kx+c, is an affine function. Linear algebra (beyond this book) builds on exactly the property that makes the rule of three work: scaling the input scales the output.
  • Means for different questions. The arithmetic mean averages amounts, the harmonic mean averages rates over equal amounts of the denominator, and the geometric mean averages growth factors (chapter 7's companion). Each is the right one when it reproduces the real total; picking a mean is picking what's held fixed.
  • Simpson's paradox and causality. Arithmetic says both comparisons are correct; which one answers "does A work better?" depends on a model of how the data arose (which factors influence which). Judea Pearl's causal diagrams make that model explicit, and randomised experiments make the paradox impossible by giving both arms the same mix on average.

Applying it

Code walkthrough

Python's statistics.harmonic_mean is the chapter's average speed as a library function, with optional weights. Excerpt from Lib/statistics.py in Python 3.13 (on your computer: python3 -c "import statistics; print(statistics.__file__)"), with its docstring shortened:

Python
def harmonic_mean(data, weights=None):
    """Return the harmonic mean of data.

    The harmonic mean is the reciprocal of the arithmetic mean of the
    reciprocals of the data.  It can be used for averaging ratios or
    rates, for example speeds.
    """
    ...
    if weights is None:
        weights = repeat(1, n)
        sum_weights = n
    else:
        ...
        _, sum_weights, _ = _sum(w for w in _fail_neg(weights, errmsg))
    try:
        data = _fail_neg(data, errmsg)
        T, total, count = _sum(w / x if w else 0 for w, x in zip(weights, data))
    except ZeroDivisionError:
        return 0
    if total <= 0:
        raise StatisticsError('Weighted sum must be positive')
    return _convert(sum_weights / total, T)

Read the last lines with speeds as the data and distances as the weights: w / x is distance ÷ speed, the time for each leg; total adds them, the total time; sum_weights is the total distance; and sum_weights / total is total distance ÷ total time. The harmonic mean with distance weights is average speed. _sum is the module's exact summation (it adds fractions exactly and converts at the end), and _convert returns the result in the input's type, so fractions in give a fraction out. Measured:

Python
from statistics import harmonic_mean, fmean
from fractions import Fraction as F
print(harmonic_mean([40, 60]), harmonic_mean([40, 60], weights=[5, 30]))
legs = [(12, 24), (180, 90), (8, 16)]                       # (km, km/h), the exercises' trip
print(harmonic_mean([v for _, v in legs], weights=[d for d, _ in legs]))
print(harmonic_mean([F(40), F(60)]), harmonic_mean([60, 0]))
hours = [d / v for d, v in legs]                              # equal-time weights give the ordinary mean
print(fmean([v for _, v in legs], weights=hours))
Text
48.0 56.0
66.66666666666667
48 0
66.66666666666667

The docstring's two examples come out as stated: 48 for equal distances, 56 when 30 of the 35 km are at 60 km/h. The exercises' city–highway–city trip gives 66.67 km/h with distance weights, and the ordinary weighted mean with time weights gives the same number: two routes to total distance over total time. Fractions stay exact (48, not 48.0). And a speed of 0 gives 0: one leg at zero speed takes for ever, so the average speed is zero, which the code handles by catching the division by zero.

Read it yourself

Using the code above, explain why harmonic_mean([60, 0]) returns 0 rather than raising an error, and whether that's the right answer for average speed. Then say what harmonic_mean([40, 60], weights=[0, 30]) returns, and why the if w else 0 matters.

Debugging drills

D1. Thumbnails with zero height

An image service makes thumbnails by scaling the height "by the same factor" as the width. Enlarging works; shrinking produces images 0 pixels tall:

Python
def thumb(w, h, new_w):
    return new_w, h * (new_w // w)          # scale the height by the same factor ... in whole numbers

for w, h, new_w in ((640, 480, 1280), (1920, 1080, 640), (1200, 800, 300)):
    print(f"{w}x{h} -> {thumb(w, h, new_w)}")
Text
640x480 -> (1280, 960)
1920x1080 -> (640, 0)
1200x800 -> (300, 0)

Explain, and fix.

D2. More workers, more days

A planning tool estimates how long a job takes with a given team size, from a base estimate of 10 days for 6 workers. Bigger teams take longer:

Python
def days_needed(workers, base_workers=6, base_days=10):
    return base_days * workers / base_workers       # "rule of three"

for n in (3, 6, 12):
    print(f"{n:>2} workers: {days_needed(n):.1f} days")
Text
 3 workers: 5.0 days
 6 workers: 10.0 days
12 workers: 20.0 days

Explain, and fix. What else should the tool say?

D3. A ratio of 28 : 57

A measuring app simplifies ratios of lengths given in metres with two decimal places. Some come out absurd:

Python
from math import gcd
def simplest(a, b):                         # a, b in metres, two decimal places
    x, y = int(a * 100), int(b * 100)
    g = gcd(x, y)
    return f"{x // g} : {y // g}"

for a, b in ((1.20, 4.80), (0.29, 0.58), (2.35, 4.70), (0.57, 1.14)):
    print(f"{a} m : {b} m -> {simplest(a, b)}")
Text
1.2 m : 4.8 m -> 1 : 4
0.29 m : 0.58 m -> 28 : 57
2.35 m : 4.7 m -> 1 : 2
0.57 m : 1.14 m -> 56 : 113

Explain, and fix.

D4. An exchange rate kept to two places

A payments table stores the dollar-to-rupee rate rounded to two decimal places, and computes the reverse rate by inverting the rounded value. Large conversions drift:

Python
from decimal import Decimal, ROUND_HALF_UP
usd_inr = Decimal("83.4567")                               # rupees per dollar, from the provider
stored = usd_inr.quantize(Decimal("0.01"), ROUND_HALF_UP)   # the table keeps 2 places
for usd in (Decimal(100), Decimal(25_000), Decimal(4_000_000)):
    right = usd * usd_inr
    used = usd * stored
    print(f"${usd:>9,}: ₹{right:,.2f} vs ₹{used:,.2f}  (off by ₹{used - right:,.2f})")
inr_usd = (1 / stored).quantize(Decimal("0.0001"), ROUND_HALF_UP)   # and the inverse, also rounded
print(f"₹1,00,000 -> ${Decimal(100000) * inr_usd:,.2f} using the rounded inverse, ${Decimal(100000) / usd_inr:,.2f} exactly")
Text
$      100: ₹8,345.67 vs ₹8,346.00  (off by ₹0.33)
$   25,000: ₹2,086,417.50 vs ₹2,086,500.00  (off by ₹82.50)
$4,000,000: ₹333,826,800.00 vs ₹333,840,000.00  (off by ₹13,200.00)
₹1,00,000 -> $1,200.00 using the rounded inverse, $1,198.23 exactly

Explain, and fix.

Career-oriented

Interview prep

Mid level

Q1. Write a function for the average speed of a trip given as legs of (distance, speed). Then explain why averaging the speeds is wrong.

How to get there. Total distance over total time; what each leg contributes.

Q2. Resize an image to fit a 400 × 300 box without distorting it. Give the algorithm and the rounding.

How to get there. One scale factor for both dimensions, the smaller of two ratios.

Senior level

Q1. Your service has 20 shards, each reporting its own p99 latency per minute. The dashboard shows the mean of the shards' p99s. Is that the service's p99? What do you change?

How to get there. Which summaries can be merged.

Q2. A shared Kubernetes cluster costs ₹12 lakh a month. Finance wants each team charged "in proportion to usage". Design the allocation.

How to get there. What usage means, fixed costs, and shares that add up.

Staff level

Q1. Define the organisation's rules for metrics that are ratios, rates and percentiles, so dashboards and alerts can be aggregated correctly across services, regions and time.

How to get there. What to store, what to derive, and how each kind merges.

Q2. A study finds a feature "increases retention" when users who used it are compared with users who didn't. You're asked to decide whether to invest in it. What do you look for?

How to get there. Simpson's paradox and confounding.