← Math
Math

Functions, composition, and piecewise rules

Why does a heavier parcel cost less?

Follow a quote from its allowed inputs through its bands and ordered transformations.

Outcome

Write a piecewise rule as a function on a declared domain, compose its steps in the stated order, and decide when an output identifies its input.

Terminology (7)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Function
A rule that assigns exactly one output to each input in its domain.
Domain
The inputs a function is defined for. Inputs outside it are invalid, not silently adjusted.
Piecewise function
A function described by formulas on different parts of its domain. Any overlapping pieces must agree; the carrier bands in this lesson assign each boundary to one band.
Continuous
Having no jump: at each boundary the adjoining pieces give the same value, even if their slopes differ.
Composition Also g ∘ f
Applying one function to the output of another. (g ∘ f)(x) = g(f(x)); order matters.
Inverse
A rule that recovers the input from the output. It exists only where different inputs never share an output.
Cap
A maximum applied with min(value, cap). Every input whose value reaches the cap shares one output.

Why this matters

Prices, tax brackets, rate limits and feature tiers are piecewise rules. A boundary in the wrong piece overcharges one customer; a band applied to the whole input makes heavier parcels cheaper; a cap in the wrong place lets totals exceed a promise. Support tools that run the rule backward need to know when they cannot.

This lesson assumes the previous ones on rates and inequalities. Money here is a mathematical model with fractional cents; settlement rounding is outside it.

Functions, pieces and composition

A function assigns exactly one output to each input in its domain, the set of allowed inputs. A piecewise function uses different formulas on different parts of that domain. The conditions select which formula applies; their boundaries must give an unambiguous result for every allowed input.

The rates and inequalities from earlier lessons supply the formulas and their conditions. Composition feeds one function’s output into another: a calculated charge can become the input to a fee or cap rule. The units must fit at each step, and changing the order can change the resulting function. Running the result backward requires checking whether more than one input could have produced it.

01Declare the domain

Declare the domain and the bands

Checkout offers lower per-kilogram rates above 2 kg and 5 kg. After a refactor, a 5 kg parcel costs 1,000 cents and a 5.1 kg parcel costs 510. Support needs to explain these quotes and work out when a saved total identifies one parcel mass.

Parcel weight bands
BandMass in the bandRate
First0 – 2 kg300 ¢/kg
Secondabove 2 – 5 kg200 ¢/kg
Thirdabove 5 – 20 kg100 ¢/kg

The domain is 0 kg through 20 kg, including fractional kilograms. A 21 kg or −1 kg parcel is invalid. Clipping it to 20 or 0 would quietly quote a parcel the carrier does not accept.

02Piece boundaries

Every boundary belongs to one piece

“Above 2 kg” means the second band starts just after 2. The value 2 itself belongs to the first band. Every allowed mass needs one rate. Overlapping pieces are harmless only when they agree; conflicting rates or a missing boundary leave the carrier's rule undefined.

Which rate applies at exactly 5 kg?

03Carry earlier bands

Carry the earlier bands into each formula

What is the weight charge for a 6 kg parcel?

Check each join. At 2 kg the first piece gives 600 and the second starts from 600. At 5 kg both adjoining pieces give 1,200. The slope changes, but the value does not jump: the charge is continuous. Charging the whole parcel at its band’s rate breaks that: 5 kg costs 1,000 at 200 ¢/kg and 5.1 kg costs 510 at 100 ¢/kg.

04Order the composition

Compose the steps in the stated order

Checkout adds a handling fee h and caps the total at K: T(w) = min(q(w) + h, K). That is a composition, add then cap, and its order is part of the rule.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const bands = [
  { upTo: 2, rate: 300 },
  { upTo: 5, rate: 200 },
  { upTo: 20, rate: 100 }
]; // kg, cents per kg

function charge(mass: number): number {
  let total = 0;
  let from = 0;

  for (const band of bands) {
    total += band.rate * Math.max(0, Math.min(mass, band.upTo) - from);
    from = band.upTo;
  }

  return total;
}

const [handling, cap] = [150, 1300]; // cents

console.log(`charge ${charge(6)}`);
console.log(`cap the total ${Math.min(charge(6) + handling, cap)}`);
console.log(`cap the charge ${Math.min(charge(6), cap) + handling}`);

Math.min returns the smaller number. Applying it after adding handling caps the total; applying it to the charge alone caps only part of the sum.

For 6 kg with h = 150 and K = 1,300, capping the total gives 1,300. Capping the charge and then adding handling gives 1,450, a total above the promised cap.

A 4 kg parcel has a 100-cent handling fee and a 1,050-cent cap on the total. What is the quote?

05Invert a capped rule

When does a quote identify the parcel?

Support sometimes runs the rule backward: which mass produced this quote? Below the cap, T is strictly increasing, so each total comes from one mass. With h = 100 and K = 1,050, a quote of 900 means q = 800, which lies in the second band: 2 + 200 ÷ 200 = 3 kg.

At the cap the rule forgets information. Every parcel whose uncapped total reaches 1,050 is quoted 1,050, from 3.75 kg (where q = 950) up to 20 kg, so no single mass can be recovered. Two edge cases matter. If the cap equals the uncapped 20 kg total exactly, only 20 kg reaches it. If the cap is higher than any total the domain can produce, a quote equal to the cap is impossible.

The lowest possible quote is T(0) = min(h, K), not always the handling fee. If handling is 150 cents but the total is capped at 100, every allowed parcel costs 100 cents. Support must report that quote as ambiguous; it is not outside the range.

With h = 100 and a cap of 2,800 cents, support sees a quote of 2,800. What mass produced it?

06Vary inputs, then decide

Vary one input at a time, then decide

Quotes with a 100-cent handling fee
CaseQuoteMass from the quote
3 kg, cap 1,0509003 kg
6 kg, cap 1,0501,050ambiguous
6 kg, cap 1,6001,4006 kg
20 kg, cap 2,8002,80020 kg
Any mass, cap 3,000at most 2,800a quote of 3,000 is invalid

07Build the quote

Build one parcel quote

Start with the band at a mass, then the progressive charge, then the support tool that runs a capped quote backward. Each level keeps the earlier working helpers, and the complete program, its types and its reader are visible.

In the frontend A quote breakdown in Next.js and Svelte Optional

A customer looking at a discount band can mistake its rate for the rate on the whole parcel. Rendering one line per band shows how much mass receives each rate. Reject an unsupported mass first: showing the first 20 kg of a 21 kg parcel would hide the domain failure behind a plausible breakdown.

The Next.js component computes the lines during render; the Svelte component uses $derived.by so the lines update when mass changes. Both reuse the same band arithmetic as the lesson.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const BANDS = [
  { upTo: 2, rate: 300 },
  { upTo: 5, rate: 200 },
  { upTo: 20, rate: 100 }
]; // kg, cents per kg

export function QuoteBreakdown({ mass }: { mass: number }) {
  if (!Number.isFinite(mass) || mass < 0 || mass > 20) {
    return <p>Enter a parcel mass from 0 to 20 kg.</p>;
  }

  let from = 0;
  const lines = BANDS.map((band) => {
    const kg = Math.max(0, Math.min(mass, band.upTo) - from);
    from = band.upTo;

    return { kg, rate: band.rate, cents: kg * band.rate };
  }).filter((line) => line.kg > 0);

  return (
    <ul>
      {lines.map((line) => (
        <li key={line.rate}>
          {line.kg} kg × {line.rate}¢ = {line.cents}¢
        </li>
      ))}
    </ul>
  );
}

Check this idea later
f(x) = x + 10 and g(x) = 2x. What is g(f(3))?
An API reports min(requests, 1000). It reports 1000. How many requests were there?
Sources

The bands, fees and caps are a worked model, not a carrier’s published tariff.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.