Module 4 · Location, Ranking, and Exploratory Summaries Lesson 34 of 120

Median and Mode

A typical settlement delay by order and frequency.

2:22 clip1:48:02–1:50:25 in the full courseWatch on YouTube

Transcript

21 sentences · select one to jump there

Check your understanding

Does an unchanged median prove no customer had a severe delay?

Choose one answer

Code lab

Run it yourself

The lesson source in 7 languages. Edit it, run TypeScript and Python right here, and compare with the expected output.

034-median-and-mode.ts
Start from GitHub
/**
 * Fintech Math Bootcamp · Lesson 034 of 120
 * Median and Mode
 * Module 04: Location, Ranking, and Exploratory Summaries
 *
 * Scenario: A typical settlement delay by order and frequency
 * Rule:     median = middle order statistic; mode = most frequent value
 *
 * Try it:   Does an unchanged median prove no customer had a severe delay?
 *
 * Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/location-ranking-and-exploratory-summaries/median-and-mode/
 * Free course:    https://courses.thefintechbuilder.com
 * Synthetic teaching example, not financial advice or a production library.
 */

export function lesson034() {
  const x = [1, 2, 2, 4, 9].sort((a,b) => a-b);
  const mid = Math.floor(x.length / 2);
  const median = x.length % 2 ? x[mid] : (x[mid-1] + x[mid]) / 2;
  const counts = new Map<number, number>();
  for (const v of x) counts.set(v, (counts.get(v) ?? 0) + 1);
  const maxCount = Math.max(...counts.values());
  const modes = [...counts].filter(([,n]) => n===maxCount).map(([v]) => v);
  const result = {median, modes};
  return result;
}

export const checkedResult = {"median":2,"modes":[2]};

// Run this file directly: npx tsx lessons/04-location-ranking-and-exploratory-summaries/034-median-and-mode.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
  console.log(JSON.stringify(lesson034(), null, 2));
}

Your output

Press Run to execute the code in your browser.

Expected output

{
  "median": 2,
  "modes": [
    2
  ]
}

Prefer your own machine? Every file is in the course repository · open it in Codespaces.

Lesson notes

The rule

median = middle order statistic; mode = most frequent value