Skip to the content

Module 1: Data and variables

Module 2: Seeing data: charts and distributions

Module 3: The centre: mean, median and mode

Module 4: Spread: range, variance and standard deviation

Module 5: Two variables: scatter plots and correlation

Module 6: Probability

Module 7: Conditional probability and Bayes' theorem

Module 8: Random variables and expected value

Module 9: Binomial, geometric and Poisson

Module 10: Continuous distributions and the normal curve

Module 11: Sampling and the central limit theorem

Module 12: Estimating: confidence intervals

Module 13: Hypothesis tests and p-values

Module 14: Comparing groups: t-tests, chi-squared and ANOVA

Module 15: Linear regression

Module 16: Multiple and logistic regression

Module 17: Simulation, the bootstrap and permutation tests

Module 18: Bayesian statistics

Module 19: Designing studies: experiments, causation and pitfalls

Module 20: Modelling like an expert

Answer key

  1. 1. Data and variables · Variables are categories or numbers · QuizIn the class survey, which variables are categorical?B. Travels by; D. Coffee rating“Travels by” and “Coffee rating” sort people into groups. The rating’s groups have an order, but they are still groups: the gap between “poor” and “fair” is not a measured amount. Age and siblings are numbers you can average: the class is on average 20.2 years old.
  2. 1. Data and variables · Variables are categories or numbers · ProblemA café records 8 orders. For each order it writes down the drink (tea, coffee or juice), the cup size (small, medium or large), the price in dollars and the number of items bought. How many observations are there, how many variables, and how many of the variables are categorical?Observations, n= 8; Variables 4; Categorical variables 2
    1. Each order is one observation, so n=8.
    2. Four things are written down about each order: drink, size, price and number of items. That is 4 variables.
    3. The drink puts each order in a group with no order (nominal), and the size puts it in an ordered group (ordinal): both are categorical. The price and the number of items are amounts you can average, so they are numerical (the price continuous, the items a discrete count).
    4. So 2 of the 4 variables are categorical.
  3. 1. Data and variables · Counts are discrete, measurements are continuous · QuizWhich of these is a continuous variable?B. The mass of an apple, in gramsA mass can be 151.3 g or 151.32 g: any value in a range. The emails and pages are counts, so discrete. Shoe sizes are a trap: feet are continuous, but the size is chosen from a fixed list of steps, so the recorded variable is discrete (and some would call it ordinal). What matters is the values that can actually appear in your data.
  4. 1. Data and variables · Ordered categories and numbers that are only labels · QuizA team’s shirt numbers are 1, 4, 7, 9, 10 and 23. What kind of variable is the shirt number?D. NominalThe digits only name a player. Number 10 is not “more” than number 9 in any sense the data cares about, and the mean, 9, does not describe anything. It is nominal. The tempting answer, discrete, is about the digits, not about what they mean: always ask what a value stands for.
  5. 1. Data and variables · You study a sample to learn about a population · QuizA poll asks 1000 voters and finds 52% plan to vote yes. In the language of statistics, the 52% is…B. A statistic, because it was calculated from a sampleIt comes from 1000 people, a sample, so it is a statistic. The parameter is the share of all voters who plan to vote yes, which nobody knows. Ask another 1000 and you would get a slightly different statistic, perhaps 50% or 54%. Measuring how much it could wobble is a big part of this course.
  6. 1. Data and variables · A tidy table has one row per observation · QuizA table of exam results has the columns Student, Maths, Physics, Chemistry, with one mark per cell. To make it tidy for “mark by subject”, which columns should it have?B. Student, Subject, MarkIf the question is about marks across subjects, “subject” is a variable, so it gets its own column, and each row is one student in one subject. The wide table hides the subject in the column names. Which shape is tidy depends on what counts as an observation for your question, so ask that first. Packing values into one cell is never tidy.
  7. 1. Data and variables · Every measurement has error · QuizA kitchen scale always reads 15 g too heavy. You weigh a bag of flour 10 times and average the readings. What happens to the 15 g?B. It stays: the average is still about 15 g too heavyThe 15 g is systematic: every reading has it, so the average has it too. Averaging only cancels errors that point in different directions. To fix bias you need a different measurement, such as checking the scale against a known 1 kg weight (calibration). More data of the same biased kind makes you more sure of the wrong answer.
  8. 1. Data and variables · Where data comes from shapes what it can tell you · QuizA school wants to know if a new reading app improves reading scores. Which design lets it say the app caused any change?C. Randomly give the app to half the classes, and compare their scores with the other halfOnly the experiment decides who gets the app by chance, so the two groups are alike in every other way on average. Students who choose the app may already be keener readers, so the first comparison mixes up the app with keenness. Opinions and usage logs say nothing about scores without the app. Designing studies has its own module later.
  9. 1. Data and variables · A first look at a data set · ProblemFifteen students say how they travel to school: bus, walk, bus, car, bike, bus, walk, bus, bike, car, bus, walk, bus, bike, walk. Find the frequency of “bus” and of “walk”, and the share of the students who travel by bus, as a percentage.Frequency of bus 6; Frequency of walk 4; Share who travel by bus 40 %
    1. Count each group: bus appears 6 times, walk 4 times, bike 3 times and car 2 times.
    2. Check: 6+4+3+2=15, the number of students, so nothing was missed or counted twice.
    3. The share by bus is its frequency divided by the number of students:
    4. 615=0.4=40%
  10. 1. Data and variables · Try it: count and check a column · Code challengeFinish frequencies(values): return a std::map whose keys are the distinct values and whose values are how many times each appears.One solution:
    Solution
    #include <map>#include <string>#include <vector>
    std::map<std::string, int> frequencies(    const std::vector<std::string>& values) {  std::map<std::string, int> counts;  for (const std::string& value : values) {    counts[value]++;  }  return counts;}
    The first time a value is seen, counts[value] adds it to the map with a count of 0, so ++ makes it 1; each later sighting adds one more. (In many languages reading a missing key is an error or a blank, which you must start at 0 yourself.) The counts always add up to the number of observations, a quick check worth doing on real data.
  11. 1. Data and variables · Try it: count and check a column · Code challengeFinish cleanHeights(heights): return a new vector without the missing values (std::nullopt) and without any height outside 50 to 250 cm (inclusive), keeping the order.One solution:
    Solution
    #include <optional>#include <vector>
    std::vector<double> cleanHeights(    const std::vector<std::optional<double>>& heights) {  std::vector<double> clean;  for (const std::optional<double>& h : heights) {    if (h && *h >= 50 && *h <= 250) clean.push_back(*h);  }  return clean;}
    Check that there is a value first: h on its own is false for std::nullopt, and *h may only be read once you know a number is there. Asking about the value, not the number, matters: a height of 0 is impossible, but for a variable where 0 can happen, such as siblings, if (*h) would wrongly drop every 0. In real work, write down every value you removed and why: silently dropping data is how analyses go wrong, and a typo like 1755 may be better fixed than dropped.
  12. 1. Data and variables · Practice problems · ProblemA column of 10 heights, in cm, reads: 172.4, missing, 165.0, 1680, 158.2, 181.5, missing, 17.3, 169.9, 175.0. Any height outside 50 to 250 cm is impossible. How many values are missing, how many are impossible, and how many usable heights are left?Missing 2; Impossible 2; Usable 6
    1. Two cells are empty: 2 missing values.
    2. 1680 cm and 17.3 cm are outside 50 to 250 cm: 2 impossible values. The first looks like 168.0 typed without its point, the second like 173 with the point in the wrong place.
    3. That leaves 10−2−2=6 usable heights: 172.4, 165.0, 158.2, 181.5, 169.9 and 175.0.
    4. Before dropping the two impossible ones, write them down: if the typos are clear, they may be better fixed than removed.
  13. 1. Data and variables · Practice problems · ProblemA farm scale is known to read 2 kg too heavy. A sack is weighed five times: 27.1, 26.8, 27.3, 26.9 and 26.9 kg. What is the average of the readings, and what is your best estimate of the sack’s true mass?Average reading 27 kg; True mass 25 kg
    1. Add the readings and divide by how many there are:
    2. 27.1+26.8+27.3+26.9+26.95=135.05=27.0 kg
    3. The average has cancelled most of the random error, but every reading, and so the average, still carries the 2 kg bias.
    4. Subtract it: the best estimate of the true mass is 27.0−2=25.0 kg.
  14. 1. Data and variables · Practice problems · ProblemA spreadsheet has one row for each of 6 shops, and four columns, 2021, 2022, 2023 and 2024, holding each shop’s sales that year. You make it tidy, with the columns shop, year and sales. How many rows does the tidy table have, and how many columns?Rows 24; Columns 3
    1. The years are values of a variable, year, so they move out of the column names into a column of their own.
    2. Each observation is one shop in one year. There are 6 shops and 4 years, so 6×4=24 rows.
    3. The columns are the variables: shop, year and sales, so 3 columns. Check: the wide table held 6×4=24 sales figures, and the tidy one has one per row, 24.
  15. 1. Data and variables · Practice problems · ProblemA town has 24 000 voters. A poll asks 600 of them, chosen at random, and 255 say they will vote yes. What is the sample size n? What percentage of the population did the poll ask? What percentage of the sample says yes?n= 600; Share of the population asked 2.5 %; Share of the sample saying yes 42.5 %
    1. The poll asked 600 people, the sample: n=600. It wants to know about all N=24000 voters, the population.
    2. The share of the population asked is 60024000=0.025=2.5%.
    3. The share of the sample saying yes:
    4. 255600=0.425=42.5%
    5. This 42.5% is a statistic, worked out from the sample. The share of all 24 000 voters who will vote yes is the parameter: unknown, probably close to 42.5%, but not exactly it.
  16. 2. Seeing data: charts and distributions · A frequency table counts each value · QuizUsing the table, what share of the 20 students rated the coffee “fair” or worse?B. 0.35The cumulative frequency at “fair” is 7: the 2 “poor” plus the 5 “fair”. As a share, 7/20=0.35. The tempting 0.25 is only the “fair” row. Cumulative columns answer “how many at or below this value” in one look, which only makes sense when the values have an order.
  17. 2. Seeing data: charts and distributions · A frequency table counts each value · Problem25 people rate a film: 3 say poor, 6 fair, 11 good and 5 excellent. Find the relative frequency of “good” (as a decimal), the cumulative frequency at “good”, and the share of the people who rated the film “good” or worse (as a decimal).Relative frequency of good 11/25 ≈ 0.44; Cumulative frequency at good 20; Share good or worse 20/25 ≈ 0.8
    1. The relative frequency of good is its frequency over the total:
    2. 1125=0.44
    3. The cumulative frequency at good adds poor, fair and good: 3+6+11=20.
    4. “Good or worse” is exactly what that cumulative frequency counts, so the share is 20/25=0.8.
  18. 2. Seeing data: charts and distributions · Bar charts show categorical data · QuizYou chart the favourite fruit of 200 people: apple, banana, cherry, mango. How should the bars be arranged?B. From most to least popular, since the fruits have no natural orderFruit is nominal: no order is built in, so sorting by frequency is the order that helps a reader rank them. Alphabetical order is easy to make but hides the ranking. For an ordinal variable such as a rating or a school year, keep the natural order instead: sorting it by height would scramble the scale.
  19. 2. Seeing data: charts and distributions · Histograms show numerical data in bins · QuizWith bins [0,10), [10,20), [20,30), which bin holds a commute of exactly 20 minutes?B. [20, 30)The square bracket includes its edge and the round one excludes it, so [20,30) contains 20 and [10,20) stops just before it. Every value lands in exactly one bin, so the counts add up to n. Counting a boundary value in both bins is a common bug when writing histogram code by hand.
  20. 2. Seeing data: charts and distributions · Histograms show numerical data in bins · ProblemTwelve deliveries took these times, in minutes: 8, 12, 15, 20, 21, 9, 30, 18, 25, 10, 14, 29. How many fall in each of the bins [0,10), [10,20), [20,30) and [30,40)?[0,10) 2; [10,20) 5; [20,30) 4; [30,40) 1
    1. Put each time in its bin. The values on an edge go to the bin on their right: 10 to [10,20), 20 to [20,30) and 30 to [30,40).
    2. [0,10): 8 and 9, so 2. [10,20): 12, 15, 18, 10 and 14, so 5. [20,30): 20, 21, 25 and 29, so 4. [30,40): 30, so 1.
    3. Check: 2+5+4+1=12, every delivery counted exactly once.
  21. 2. Seeing data: charts and distributions · The bin width changes the story · QuizYou draw a histogram of 40 exam marks with 40 bins. What is the most likely problem?B. Most bins hold 0 or 1 value, so the shape is lost in noiseWith about one value per bin, the chart becomes a row of 0s and 1s, and its ups and downs are chance, not shape. More bins show more detail, but detail and truth are not the same with little data. The frequencies still add up to 40 whatever the bins, which is why that answer is wrong.
  22. 2. Seeing data: charts and distributions · Dot plots and stem-and-leaf plots keep every value · QuizIn the stem-and-leaf plot of exam marks, how many students scored 80 or more?B. 6The stems 8 and 9 hold the marks from 80 up: four leaves on 8 (81, 83, 84, 88) and two on 9 (90, 95), so 6. Count leaves, not stems. A stem-and-leaf plot answers questions like this exactly, where a histogram with wide bins could only give an estimate.
  23. 2. Seeing data: charts and distributions · Shape: symmetric, skewed or bimodal · QuizMost people in a town earn between 20 000 and 50 000 a year, and a handful earn several million. The histogram of incomes is…B. Skewed rightSkew is named after the tail, not the peak. The bulk is on the left and the long thin tail stretches right towards the millions, so it is skewed right. People often get this backwards because the hump is on the left. Incomes, waiting times and file sizes are nearly always skewed right: they cannot go below 0 but can be very large.
  24. 2. Seeing data: charts and distributions · A box plot draws five numbers · QuizRoughly what share of the commutes are between 12 and 27 minutes, the two ends of the box?B. 50%By definition the box runs from the lower quartile to the upper quartile, so it holds the middle half of the data, whatever its length. A long box means the middle half is spread out, not that it holds more people. The right whisker is longer than the left, and the median sits left of the box’s centre: both are signs of skew to the right.
  25. 2. Seeing data: charts and distributions · Charts can mislead · QuizAn advert’s bar chart shows two brands at 50% and 52%, with the y-axis running from 49% to 53%. How many times taller is the second bar drawn than the first?B. 3 timesBars are drawn from the axis’s bottom, 49%. The first bar is 50−49=1 unit tall and the second 52−49=3, so the second looks 3 times taller, while the real ratio is 52/50=1.04. For a line chart, a zoomed axis can be fine, since the eye reads position, not length; for bars, start at 0.
  26. 2. Seeing data: charts and distributions · Try it: count values into bins · Put in orderPut the steps of drawing a histogram by hand in order.1. Find the smallest and largest values 2. Choose a bin width and the first bin’s left edge 3. Count the values in each bin, edges going to the bin on their right 4. Check that the counts add up to n 5. Draw touching bars, one per binYou need the range before choosing bins that cover it, and the bins before you can count. The check that counts add up to n catches values counted twice or missed at the edges, so it comes before drawing.
  27. 2. Seeing data: charts and distributions · Try it: count values into bins · Code challengeFinish binCounts(values, start, width, bins): return a vector of bins counts, where bin i holds the values v with start + i * width <= v < start + (i + 1) * width. Values outside every bin are ignored.One solution:
    Solution
    #include <cmath>#include <vector>
    std::vector<int> binCounts(const std::vector<double>& values,                           double start, double width, int bins) {  std::vector<int> counts(bins, 0);  for (double v : values) {    int i = std::floor((v - start) / width);    if (i >= 0 && i < bins) counts[i]++;  }  return counts;}
    (v - start) / width says how many widths v is past the start, and std::floor turns that into the bin number: 15 with bins of 10 is 1.5 widths in, so bin 1. Flooring is what makes the left edge belong to the bin: 10 is exactly 1.0, so bin 1, not bin 0. Storing the quotient straight into an int would cut the fraction off towards zero, putting −3 (−0.3 widths) in bin 0; std::floor rounds down to −1, which is dropped. Checking i < bins drops values past the last bin; without it, counts[3]++ on a vector of 3 would write past its end, which stops the program here and quietly corrupts memory elsewhere.
  28. 2. Seeing data: charts and distributions · Try it: count values into bins · Code challengeFinish relativeFrequencies(counts): return each count divided by the total of all the counts. If the total is 0, return all zeros.One solution:
    Solution
    #include <vector>
    std::vector<double> relativeFrequencies(    const std::vector<int>& counts) {  int total = 0;  for (int c : counts) total += c;  std::vector<double> shares(counts.size(), 0.0);  if (total == 0) return shares;  for (std::size_t i = 0; i < counts.size(); i++) {    shares[i] = double(counts[i]) / total;  }  return shares;}
    Add up the counts once, then divide each by that total. Both are ints, so counts[i] / total would be integer division: 2 / 20 is 0, and every share but a whole one comes out 0. double(counts[i]) makes the division decimal. A total of 0 would make every share 0.0 / 0, which is nan (and with two ints, a division by zero that stops the program), so that case is handled first. The tests use EXPECT_NEAR because decimals like 0.45 cannot be stored exactly in binary, so arithmetic on them can land a hair off (0.1 + 0.2 is 0.30000000000000004, and shares may add up to 0.9999999999999999): compare decimals with a tolerance, never with exact equality.
  29. 2. Seeing data: charts and distributions · Practice problems · ProblemA stem-and-leaf plot of 15 test marks (key: 6 | 3 means 63) has these rows: 4 | 7 9, 5 | 2 5 8, 6 | 0 3 3 6 9, 7 | 1 4 8 and 8 | 2 5. How many marks are in the 60s, how many are 70 or more, and what is the median mark?Marks in the 60s 5; Marks of 70 or more 5; Median 63
    1. The stem 6 has five leaves, 0 3 3 6 9: the marks 60, 63, 63, 66 and 69. So 5 marks are in the 60s.
    2. Marks of 70 or more sit on the stems 7 and 8: three leaves (71, 74, 78) plus two (82, 85), so 5.
    3. In order the marks are 47, 49, 52, 55, 58, 60, 63, 63, … The middle of 15 values is the 8th, with 7 on each side: the median is 63.
  30. 2. Seeing data: charts and distributions · Practice problems · ProblemA bar chart shows this year’s sales, 126, beside last year’s, 120. Its y-axis starts at 110. How many times taller is this year’s bar drawn, and what is the true ratio of the two sales figures?Drawn ratio 1.6; True ratio 1.05
    1. The bars start at the axis’s bottom, 110. This year’s bar is 126−110=16 units tall and last year’s 120−110=10.
    2. So it is drawn 16/10=1.6 times taller: it looks like growth of 60%.
    3. The true ratio is 126/120=1.05: growth of 5%. An axis starting at 0 would show that honestly.
  31. 2. Seeing data: charts and distributions · Practice problems · ProblemA box plot of 200 commute times has Q1=14, median 22 and Q3=35 minutes. About how many of the commutes are under 14 minutes, how many are between 14 and 35 minutes, and how many are over 22 minutes?Under 14 minutes 50; Between 14 and 35 minutes 100; Over 22 minutes 100
    1. About a quarter of the values are below Q1: 200/4=50 commutes under 14 minutes.
    2. The box, from Q1 to Q3, holds the middle half: about 200/2=100 commutes between 14 and 35 minutes.
    3. About half the values are above the median: about 100 commutes over 22 minutes.
    4. These are “about”, because values can tie with a quartile, and methods for quartiles differ a little.
  32. 2. Seeing data: charts and distributions · Practice problems · ProblemA poster shows sales growing by 50% by drawing this year’s coin 1.5 times as wide and 1.5 times as tall as last year’s. How many times bigger does the new coin’s area look? By what factor should the width and the height have been scaled, so that the area grew by exactly 50%?Area factor 2.25; Honest scale factor sqrt(1.5) ≈ 1.22474
    1. Scaling the width and the height by 1.5 multiplies the area by 1.5×1.5=2.25: the coin looks 125% bigger, not 50%.
    2. To make the area 1.5 times as big, scale each side by k, where k2=1.5:
    3. k=1.5≈1.22
    4. Better still, draw bars: people judge lengths far more accurately than areas.
  33. 3. The centre: mean, median and mode · The mean shares the total out equally · QuizFour parcels have a mean mass of 2 kg. A fifth parcel of 7 kg is added. What is the new mean?B. 3 kgWork with totals: four parcels of mean 2 kg weigh 8 kg together. Add 7 kg and the total is 15 kg over 5 parcels, so 15/5=3 kg. The tempting 4.5 kg is the mean of 2 and 7, which treats the four old parcels as if they were one. Converting a mean back into a total, nx‾, is the trick behind many mean questions.
  34. 3. The centre: mean, median and mode · The mean shares the total out equally · ProblemFive quiz scores have a mean of 72. Four of them are 65, 80, 70 and 74. What is the fifth?The fifth score 71
    1. Five scores with mean 72 add up to 5×72=360.
    2. The four you know add up to 65+80+70+74=289.
    3. So the fifth is 360−289=71. Check: (289+71)/5=360/5=72.
  35. 3. The centre: mean, median and mode · The mean shares the total out equally · Code challengeFinish mean(values): return the sum of the values divided by how many there are.One solution:
    Solution
    #include <vector>
    double mean(const std::vector<double>& values) {  double sum = 0;  for (double v : values) sum += v;  return sum / values.size();}
    Add up in a loop, then divide once at the end. sum is a double, so the division keeps its fraction; an int sum of whole numbers would divide as whole numbers, and the mean of 3, 4, 5, 5 and 7 would come out 4 instead of 4.8. The decimal test is why the tests use EXPECT_NEAR: 0.1+0.2+0.3 in binary floating point is 0.6000000000000001, so its mean is not exactly 0.2. An empty vector gives 0.0 / 0, which is nan (not a number): the mean of nothing is undefined, and returning nan says so.
  36. 3. The centre: mean, median and mode · The median is the middle value · QuizWhat is the median of 12, 7, 3, 9, 15, 4?B. 8Sort first: 3, 4, 7, 9, 12, 15. There are 6 values, so the two middle ones are the 3rd and 4th, 7 and 9, and the median is 7+92=8. Taking the middle of the list as given, 3 and 9, is the classic mistake: the median is about order, so sorting comes first, always.
  37. 3. The centre: mean, median and mode · The median is the middle value · ProblemFind the median of 14, 3, 9, 21, 6, 11, 8, 17. Then a ninth value, 2, is added: what is the median now?Median of the 8 values 10; Median with 2 added 9
    1. Sorted: 3, 6, 8, 9, 11, 14, 17, 21. With 8 values, the two middle ones are the 4th and 5th, 9 and 11:
    2. median=9+112=10
    3. With 2 added: 2, 3, 6, 8, 9, 11, 14, 17, 21. Now n=9, and the median is at position 9+12=5: the value 9.
    4. One new small value moved the median only from 10 to 9.
  38. 3. The centre: mean, median and mode · Computing the median in code · Find the bugThis median of whole numbers works for {3, 5, 4}, but returns 8 for {10, 9, 2, 8} instead of 8.5, and 1 for {1, 2} instead of 1.5. Which line is wrong?Line 6: return (sorted[mid - 1] + sorted[mid]) / 2.0;The two middle values are ints, so their sum, 17, is an int, and 17 / 2 is integer division: 8, with the half cut off. The function returns a double, but the conversion only happens after the damage is done. Dividing by 2.0 makes the division decimal. Line 4’s sorted.size() / 2 is integer division too, and there it is exactly right: 5 values give mid 2, the middle index. The copy on line 2 is right as well: a median should not reorder its caller’s data.
  39. 3. The centre: mean, median and mode · Computing the median in code · Code challengeFinish median(values): sort a copy of the values, then return the middle one, or the mean of the two middle ones when there is an even number. Do not change the vector you are given.One solution:
    Solution
    #include <algorithm>#include <vector>
    double median(const std::vector<double>& values) {  std::vector<double> sorted = values;  // a copy  std::sort(sorted.begin(), sorted.end());  std::size_t mid = sorted.size() / 2;  if (sorted.size() % 2 == 1) return sorted[mid];  return (sorted[mid - 1] + sorted[mid]) / 2;}
    For 6 values, mid is 3, so the two middle ones are at indexes 2 and 3 (vectors count from 0). For 5 values, mid is 2, because 5 / 2 between whole numbers drops the half: the third value, exactly the middle. The values themselves are doubles, so halving their sum keeps its fraction. values is const, so the function cannot sort it; copying it into sorted keeps the caller’s data in its order. Sorting is the slow part, about nlog⁡n steps; there are cleverer ways to find a median without a full sort (std::nth_element), but this is the clear one.
  40. 3. The centre: mean, median and mode · The mode is the most common value · QuizA shoe shop wants to know which size to reorder most of. Last month it sold sizes 38, 39, 39, 40, 41, 41, 41, 42, 44, 46. Which measure answers its question, and what is it?C. The mode, 41The shop needs the size people buy most often: the mode, 41, which sold three pairs. The mean happens to be close here, 411/10=41.1, but it can be a size nobody wears, and with a wider spread of sizes it could easily land on a size that sells little. The median is also 41 here; it is the mode that answers “which one most often”.
  41. 3. The centre: mean, median and mode · One extreme value drags the mean · QuizA data set of nine heights has median 171 cm and mean 172 cm. One height of 180 cm was mistyped as 1800 cm. Which measure is badly wrong?B. Only the meanThe typo adds 1800−180=1620 cm to the total, so the mean jumps by 1620/9=180 cm, to about 352 cm, an impossible average height. The median depends only on which value is in the middle: 180 cm and 1800 cm are both above 171 cm, so the middle value does not change. This is also why a mean far from the median is a hint to look for errors.
  42. 3. The centre: mean, median and mode · Skew pulls the mean towards the tail · QuizA news report says the mean house price in a city is 450 000 and the median is 310 000. What does that suggest?B. The prices are skewed right: a few very expensive housesThe mean is well above the median, so something is pulling it up: a tail of expensive houses, a right skew. The median says a typical house costs about 310 000; the mean is what you would get if all the money spent were shared out equally, which no buyer pays. This is why official statistics on prices and incomes quote the median.
  43. 3. The centre: mean, median and mode · A weighted mean lets some values count more · Code challengeFinish weightedMean(values, weights): multiply each value by the weight at the same index, add those up, and divide by the sum of the weights.One solution:
    Solution
    #include <vector>
    double weightedMean(const std::vector<double>& values,                    const std::vector<double>& weights) {  double total = 0;  double weightSum = 0;  for (std::size_t i = 0; i < values.size(); i++) {    total += values[i] * weights[i];    weightSum += weights[i];  }  return total / weightSum;}
    Keep two running totals, the weighted sum and the sum of the weights, and divide once. Dividing by the number of values instead of the weight sum only works when the weights add up to the count; with the class sizes it would give 3100/2=1550. Weights that already add up to 1, like percentages, make the division by 1 harmless.
  44. 3. The centre: mean, median and mode · A trimmed mean drops the extremes · Fill the blanksFinish trimmedMean, which drops k values from each end of the sorted data.1: begin(), 2: k, 3: k, 4: size()std::sort(values.begin(), values.end()) sorts the whole vector, from its first value to its end. kept(values.begin() + k, values.end() - k) copies the values from index k up to, but not including, the k last ones, so k values are dropped at each end. Divide by the number kept, not by values.size(): dividing 38 by 10 would give 3.8, below almost every value. values comes without &, so it is the function’s own copy: sorting it leaves the caller’s data alone.
  45. 3. The centre: mean, median and mode · Choosing a measure of centre · QuizA city plans water supply and needs to know how much water its 100 000 homes use in total. Which average of household use is the one to multiply by 100 000?B. The meanOnly the mean is tied to the total: total=nx‾. The few homes with pools really do use that water, and the plan must supply it. The median would describe a typical home better, but multiplying it by 100 000 underestimates the total for right-skewed use. The right measure depends on the question, not only on the shape.
  46. 3. The centre: mean, median and mode · Practice problems · ProblemA team scored these numbers of goals in 10 matches: 2, 0, 3, 1, 12, 2, 4, 1, 3, 2. Find the mean, the median and the mode.Mean 3; Median 2; Mode 2
    1. The total is 2+0+3+1+12+2+4+1+3+2=30, so the mean is 30/10=3 goals.
    2. Sorted: 0, 1, 1, 2, 2, 2, 3, 3, 4, 12. The 5th and 6th values are 2 and 2, so the median is 2.
    3. The value 2 appears three times, more than any other: the mode is 2.
    4. The mean is above the median because of the one 12-goal match. A typical match had about 2 goals.
  47. 3. The centre: mean, median and mode · Practice problems · ProblemA course counts homework 25%, a project 25% and the final exam 50%. A student scores 88 on homework, 72 on the project and 65 on the final. What is the course grade? What final-exam mark would have given a grade of exactly 75?Course grade 72.5; Final mark for 75 70
    1. x‾w=0.25×88+0.25×72+0.5×65=22+18+32.5=72.5
    2. For a grade of 75 with a final mark F:
    3. 22+18+0.5F=75⇒0.5F=35⇒F=70
    4. The final carries half the weight, so 5 more marks on it lift the grade by 2.5.
  48. 3. The centre: mean, median and mode · Practice problems · ProblemOne class of 12 students has a mean mark of 68; another class of 18 students has a mean of 78. What is the mean mark of all 30 students together?Mean of all 30 74
    1. The totals are 12×68=816 and 18×78=1404.
    2. x‾=816+140430=222030=74
    3. Not 68+782=73: the bigger class pulls the combined mean towards its 78. It is a weighted mean, with the class sizes as the weights.
  49. 3. The centre: mean, median and mode · Practice problems · ProblemTen delivery times, in minutes: 12, 15, 9, 14, 48, 13, 16, 11, 14, 38. Find the mean, the median and the 20% trimmed mean.Mean 19 min; Median 14 min; 20% trimmed mean 14 min
    1. Sorted: 9, 11, 12, 13, 14, 14, 15, 16, 38, 48. The total is 190, so the mean is 190/10=19 minutes.
    2. The 5th and 6th values are 14 and 14, so the median is 14 minutes.
    3. Drop 9 and 11 at the bottom and 38 and 48 at the top. The six values left add up to 12+13+14+14+15+16=84:
    4. 20% trimmed mean=846=14
    5. Two slow deliveries lift the mean 5 minutes above the other two summaries: the median or the trimmed mean is the better typical time.
  50. 4. Spread: range, variance and standard deviation · The centre is not the whole story · QuizTwo trains both arrive on average exactly on time. Train A is always within 1 minute; train B is often 15 minutes early or late. Which statement is right?B. Train B has the larger spread, and is less reliableReliability is about spread, not centre: both means are zero minutes late, but B’s arrival times vary far more. An average of “on time” can hide early and late trains cancelling out. Whenever you see a mean, ask how spread out the values around it are.
  51. 4. Spread: range, variance and standard deviation · The range is simple but fragile · QuizNine students’ reaction times are between 0.21 s and 0.30 s. A tenth student sneezes and records 1.40 s. What happens to the range?B. It goes from 0.09 s to 1.19 sBefore: 0.30−0.21=0.09 s. After, the maximum is 1.40 s, so the range is 1.40−0.21=1.19 s, more than 13 times bigger, because of one value. The range is not resistant. The measures in the next slides use all the values, or only the middle ones, to avoid this.
  52. 4. Spread: range, variance and standard deviation · Quartiles and the interquartile range · QuizWhat is the IQR of 1, 3, 4, 6, 7, 9, 10, 15 using the median-of-halves method?B. 6With 8 values, the halves are 1, 3, 4, 6 and 7, 9, 10, 15. Q1 is the median of the lower half, 3+42=3.5, and Q3=9+102=9.5, so IQR=9.5−3.5=6. 14 is the range. With an even n no value is left out: the median, 6.5, falls between the two halves.
  53. 4. Spread: range, variance and standard deviation · Quartiles and the interquartile range · ProblemNine values, sorted: 4, 7, 8, 10, 12, 15, 16, 21, 40. Using the median-of-halves method, find Q1, Q3, the IQR and the range.Q1= 7.5; Q3= 18.5; IQR 11; Range 36
    1. The median is the 5th value, 12. The lower half is 4, 7, 8, 10 and the upper half is 15, 16, 21, 40.
    2. Q1=7+82=7.5Q3=16+212=18.5
    3. So IQR=18.5−7.5=11, and the range is 40−4=36.
    4. The range is more than three times the IQR, and almost all of that comes from the single value 40.
  54. 4. Spread: range, variance and standard deviation · The 1.5 × IQR rule flags outliers · Fill the blanksFinish fences, which returns the lower and upper fences for the quartiles q1 and q3.1: q3 - q1, 2: 1.5, 3: q3The IQR is Q3−Q1, never negative. The lower fence goes down from Q1 and the upper fence up from Q3, each by 1.5 IQRs. Measuring both fences from the median is a common slip: it ignores skew, which the quartiles capture.
  55. 4. Spread: range, variance and standard deviation · The 1.5 × IQR rule flags outliers · ProblemFor the nine values 4, 7, 8, 10, 12, 15, 16, 21, 40, with Q1=7.5 and Q3=18.5, find the lower and upper fences, and the value where the upper whisker of the box plot stops.Lower fence -9; Upper fence 35; Upper whisker stops at 21
    1. The IQR is 18.5−7.5=11, and 1.5×11=16.5.
    2. lower fence=7.5−16.5=−9upper fence=18.5+16.5=35
    3. No value is below −9. The value 40 is above 35, so it is flagged and drawn as a point. The largest value inside the fence is 21, so the upper whisker stops at 21.
  56. 4. Spread: range, variance and standard deviation · A sample divides by n − 1 · QuizYou measure 12 apples picked at random from an orchard to estimate how much apple masses vary across the whole orchard. Which do you divide the sum of squared deviations by?B. 11The 12 apples are a sample and the orchard is the population, so divide by n−1=11. Dividing by 12 would give the variance of these 12 apples exactly, but would underestimate the orchard’s, on average by a factor of 1112. When the data is the whole population, say every employee of a firm, divide by N.
  57. 4. Spread: range, variance and standard deviation · Try it: the sample standard deviation · Find the bugThis returns 0 for every data set. Which line is wrong?Line 7: for (double v : values) sum += (v - mean) * (v - mean);The deviations from the mean always add up to 0, up to rounding, so without squaring the sum is (close to) 0 for any data. Squaring makes every deviation count positively. C++ has no power operator: square with d * d or std::pow(d, 2), never d ^ 2, which is bitwise XOR (on ints it quietly gives a wrong number; on doubles it does not compile). Using std::abs(v - mean) would also stop the cancelling, but gives the mean absolute deviation, a different measure.
  58. 4. Spread: range, variance and standard deviation · Try it: the sample standard deviation · Code challengeFinish sampleSd(values): compute the mean, add up the squared deviations from it, divide by n - 1, and return the square root.One solution:
    Solution
    #include <cmath>#include <vector>
    double sampleSd(const std::vector<double>& values) {  int n = values.size();  double mean = 0;  for (double v : values) mean += v;  mean /= n;  double sum = 0;  for (double v : values) sum += (v - mean) * (v - mean);  return std::sqrt(sum / (n - 1));}
    For bakery B the deviations are −40, −20, 0, 20, 40, their squares add to 4000, and 4000/4=1000≈31.62 g. Dividing by n would give 800≈28.28: close, but too small. sum is a double, so sum / (n - 1) keeps its fraction even though n - 1 is an int. Forgetting the square root leaves the variance, 1000 square grams, which is the wrong unit as well as the wrong size.
  59. 4. Spread: range, variance and standard deviation · A z-score measures distance in standard deviations · Code challengeFinish zScores(values, mean, sd): return each value’s z-score, in the same order.One solution:
    Solution
    #include <vector>
    std::vector<double> zScores(const std::vector<double>& values,                            double mean, double sd) {  std::vector<double> z;  for (double x : values) z.push_back((x - mean) / sd);  return z;}
    Subtract first, then divide: (x - mean) / sd. Without the brackets, x - mean / sd divides only the mean, giving 78−17.5. Turning a whole data set into z-scores is called standardising; the result always has mean 0 and standard deviation 1, which is why many methods standardise first.
  60. 4. Spread: range, variance and standard deviation · The 68–95–99.7 rule for bell-shaped data · QuizAdult heights in a country are bell-shaped with mean 170 cm and SD 7 cm. About what share of adults are taller than 184 cm?B. 2.5%184 cm is 184−1707=2 SDs above the mean. About 95% are within 2 SDs, so 5% are outside, and by symmetry half of that, 2.5%, are above. The tempting 5% counts both tails. Draw the curve and shade the part you want: it prevents most mistakes with the rule.
  61. 4. Spread: range, variance and standard deviation · Chebyshev’s inequality works for any shape · QuizDelivery times have mean 30 minutes and SD 5 minutes, and you know nothing about their shape. What can you say for certain about deliveries between 20 and 40 minutes?B. At least 75% of them20 to 40 is 2 SDs either side, so k=2 and Chebyshev guarantees at least 1−14=75%. The 95% needs a bell shape, which you were not told; delivery times are usually skewed right, so it might not hold. “At least” is the point: the true share is often higher.
  62. 4. Spread: range, variance and standard deviation · Practice problems · ProblemA sample of five parcels weighs 6, 8, 9, 11 and 16 kg. Find the mean, the sample variance s2 and the sample standard deviation s. Then find the variance you would get if these five parcels were the whole population, dividing by N.x‾= 10 kg; s2= 14.5 kg²; s= sqrt(14.5) ≈ 3.80789 kg; σ2= 11.6 kg²
    1. The mean is x‾=50/5=10 kg. The deviations are −4, −2, −1, 1 and 6 (they add up to 0), and their squares are 16, 4, 1, 1 and 36.
    2. ∑(xi−x‾)2=16+4+1+1+36=58
    3. s2=585−1=14.5 kg2s=14.5≈3.81 kg
    4. As a whole population, divide by N=5 instead: σ2=58/5=11.6 kg2, a little smaller.
  63. 4. Spread: range, variance and standard deviation · Practice problems · ProblemIn a running club, 100 m times have mean 13.0 s and SD 0.4 s, and long jumps have mean 5.0 m and SD 0.5 m. Mia runs 100 m in 12.4 s and jumps 5.6 m. Find the z-score of each result.z for the run −1.5; z for the jump 1.2
    1. zrun=12.4−13.00.4=−1.5zjump=5.6−5.00.5=1.2
    2. Her time is 1.5 SDs below the mean, and in a race a lower time is better. Her jump is 1.2 SDs above the mean.
    3. So the run is the more unusual result: 1.5 SDs better than average, against 1.2 for the jump.
  64. 4. Spread: range, variance and standard deviation · Practice problems · ProblemThe weights of bags of flour are bell-shaped, with mean 500 g and SD 10 g. Using the 68–95–99.7 rule, about what percentage of bags weigh between 480 and 520 g? More than 510 g? Between 490 and 520 g?480 to 520 g 95 %; Over 510 g 16 %; 490 to 520 g 81.5 %
    1. 480 and 520 g are at z=−2 and z=2: about 95% of bags.
    2. 510 g is at z=1. 68% of bags lie within 1 SD, so 100−68=32% lie outside, half of them above: 16%.
    3. From 490 g (z=−1) to 500 g is half of 68%, 34%; from 500 g to 520 g (z=2) is half of 95%, 47.5%:
    4. 34%+47.5%=81.5%
  65. 4. Spread: range, variance and standard deviation · Practice problems · ProblemWaiting times at a clinic have mean 40 minutes and SD 6 minutes, and you know nothing about their shape. What is the smallest percentage of waits that Chebyshev’s inequality guarantees are between 28 and 52 minutes? Between 31 and 49 minutes?28 to 52 minutes 75 %; 31 to 49 minutes 500/9 ≈ 55.5556 %
    1. 28 and 52 are 12/6=2 SDs either side of 40, so k=2: at least 1−14=75%.
    2. 31 and 49 are 9/6=1.5 SDs either side, so k=1.5:
    3. 1−11.52=1−12.25=59≈55.6%
    4. These are guarantees for any shape. If the waits were bell-shaped, the true shares would be about 95% and 87%.
  66. 5. Two variables: scatter plots and correlation · A scatter plot shows two numerical variables · QuizYou study whether the outside temperature affects how many ice creams a kiosk sells each day. Which goes on the x-axis?B. TemperatureTemperature is the explanatory variable: the idea is that it drives sales, not the other way round. So it goes across and sales go up. Swapping them does not change the points’ pattern or the correlation, but it does change a fitted line (regression, a later module), and readers expect the cause-like variable on x.
  67. 5. Two variables: scatter plots and correlation · Describe direction, form and strength · QuizFor used cars, the older the car, the lower its price, and the points lie close to a gently curving line. How would you describe it?B. Negative, curved, strongPrice falls as age rises: negative. The points follow a curve (cars lose value fast at first, then slowly): curved form. They lie close to it: strong. Direction, form and strength are separate questions; a relationship can be strong and still not linear, which matters because the correlation coefficient only measures straight lines.
  68. 5. Two variables: scatter plots and correlation · Covariance: do the deviations agree · QuizMost points of a scatter plot lie above and left of the means, or below and right of them. The covariance is…B. NegativeAbove and left means x−x‾<0 and y−y‾>0: a negative product. Below and right gives positive times negative: negative again. So the sum, and the covariance, is negative, and y tends to fall as x rises. The sign of each product is the sign of “do x and y agree about being above average?”.
  69. 5. Two variables: scatter plots and correlation · Covariance: do the deviations agree · ProblemFive points have x = 2, 4, 6, 8, 10 and y = 5, 9, 7, 13, 11. Find y‾, the sum of the products of deviations ∑(xi−x‾)(yi−y‾), and the sample covariance sxy.y‾= 9; Sum of products 32; sxy= 8
    1. The means are x‾=30/5=6 and y‾=45/5=9.
    2. The deviations of x are −4, −2, 0, 2, 4, and of y are −4, 0, −2, 4, 2. Their products are 16, 0, 0, 8 and 8.
    3. ∑(xi−x‾)(yi−y‾)=16+0+0+8+8=32sxy=325−1=8
    4. Positive: the points sit mostly where x and y are both above, or both below, their means.
  70. 5. Two variables: scatter plots and correlation · Correlation is covariance without units · QuizWhich of these are true of Pearson’s r?B. Swapping x and y leaves r the same; D. r has no unitsThe formula is symmetric in x and y, so swapping them changes nothing, and dividing by both standard deviations cancels every unit: rescaling a variable (metres for centimetres, °F for °C) leaves r alone. r=0.8 is not a percentage of points; it is a measure of how tightly the points follow a line. (Its square, 0.64, has a meaning in regression, later.)
  71. 5. Two variables: scatter plots and correlation · Correlation is covariance without units · ProblemFive points have x = 1, 2, 3, 4, 5 and y = 10, 8, 9, 5, 3. Find ∑(xi−x‾)(yi−y‾), ∑(yi−y‾)2, and Pearson’s r.Sum of products -17; ∑(yi−y‾)2= 34; r= -17/sqrt(340) ≈ −0.921954
    1. The deviations of x are −2, −1, 0, 1, 2, and of y are 3, 1, 2, −2, −4.
    2. The products are −6, −1, 0, −2 and −8, which add up to −17. The squared y deviations are 9, 1, 4, 4 and 16, which add up to 34.
    3. r=−1710×34=−17340≈−0.922
    4. A strong negative linear relationship: y falls as x rises, and the points lie close to a line.
  72. 5. Two variables: scatter plots and correlation · Correlation only sees straight lines · QuizA report says the correlation between two variables is r=0.02. What can you conclude?B. There is little or no linear relationship; there could still be a curved oner near 0 rules out a straight-line pattern, nothing more. The parabola above has r=0 and a perfect relationship. Statisticians say “uncorrelated” for r=0, which is weaker than “independent”. The famous Anscombe’s quartet is four data sets with the same means, SDs and r=0.82, whose scatter plots look completely different.
  73. 5. Two variables: scatter plots and correlation · Try it: compute the correlation · Code challengeFinish correlation(xs, ys): return Pearson’s r, the sum of the products of deviations divided by the square root of the product of the two sums of squared deviations.One solution:
    Solution
    #include <cmath>#include <vector>
    double correlation(const std::vector<double>& xs,                   const std::vector<double>& ys) {  int n = xs.size();  double mx = 0, my = 0;  for (int i = 0; i < n; i++) {    mx += xs[i];    my += ys[i];  }  mx /= n;  my /= n;  double sxy = 0, sxx = 0, syy = 0;  for (int i = 0; i < n; i++) {    sxy += (xs[i] - mx) * (ys[i] - my);    sxx += (xs[i] - mx) * (xs[i] - mx);    syy += (ys[i] - my) * (ys[i] - my);  }  return sxy / std::sqrt(sxx * syy);}
    One loop builds all three sums. The n−1 of the covariance and of both standard deviations cancel, so they never appear. Common slips: dividing by std::sqrt(sxx) * syy (forgetting to root both), or using raw values instead of deviations, which gives a number that changes when you shift the data. If every x is the same, sxx is 0 and r is 0.0 / 0, which is nan: no spread in x, no correlation to speak of.
  74. 5. Two variables: scatter plots and correlation · Rank correlation for any rising pattern · Code challengeFinish ranks(values): return the rank of each value, in the original order, where the smallest value has rank 1. You can assume there are no ties.One solution:
    Solution
    #include <algorithm>#include <utility>#include <vector>
    std::vector<int> ranks(const std::vector<double>& values) {  std::vector<std::pair<double, int>> order;  // value, index  for (int i = 0; i < values.size(); i++) {    order.push_back({values[i], i});  }  std::sort(order.begin(), order.end());  std::vector<int> result(values.size());  for (int position = 0; position < order.size(); position++) {    result[order[position].second] = position + 1;  }  return result;}
    Sort pairs of value and original index (std::sort orders pairs by their first, the value), then give each pair its position plus one, written back at its original index, its second. Sorting the values alone loses track of where each came from. With ties, the usual rule gives tied values the mean of the ranks they share (two values tied for 2nd and 3rd both get 2.5).
  75. 5. Two variables: scatter plots and correlation · Two-way tables relate two categorical variables · QuizOf the people who prefer tea, what share are 30 or over?B. 78%Now the group is “prefers tea”, the column, so divide by the column total: 70/90≈78%. The 58% answers a different question, the share of over-30s who prefer tea (70/120). The two are easy to swap, and swapping them is the root of many famous errors, as the next module on conditional probability shows.
  76. 5. Two variables: scatter plots and correlation · Correlation is not causation · QuizAcross towns, the number of fire engines sent to a fire is positively correlated with the damage it does. What best explains this?B. A lurking variable: bigger fires get more engines and do more damageThe size of the fire drives both: big fires need many engines and cause much damage. Sending fewer engines would not reduce damage; it would increase it. Before reading a correlation as cause and effect, always ask what else could move both variables. Only a randomised experiment rules out lurking variables reliably.
  77. 5. Two variables: scatter plots and correlation · Simpson’s paradox: the trend can reverse · QuizYou have a kidney stone of unknown size. Based on this data, which treatment should you prefer?B. A, because it is better for each size of stoneWhatever your stone’s size, A did better for that size, so A is the better bet. The overall rate compares unlike groups: B’s patients were mostly easy cases. Simpson’s paradox is not a contradiction; it is a warning that combining groups can mix in a lurking variable. Which way to read the data depends on what causes what, which is why the later module on study design draws causal diagrams.
  78. 5. Two variables: scatter plots and correlation · Practice problems · ProblemTwo judges rank five bakers. Judge A ranks them 1, 2, 3, 4, 5, and judge B ranks the same five bakers, in the same order, 2, 1, 4, 3, 5. Find ∑di2 and Spearman’s rs.∑di2= 4; rs= 0.8
    1. The differences are 1−2=−1, 2−1=1, 3−4=−1, 4−3=1 and 5−5=0. Their squares add up to 1+1+1+1+0=4.
    2. rs=1−6×45(52−1)=1−24120=0.8
    3. The judges agree closely: they only swap two pairs of neighbours.
  79. 5. Two variables: scatter plots and correlation · Practice problems · ProblemOf 300 shoppers, 120 saw an advert, and 48 of those bought the product. Of the 180 who did not see it, 36 bought it. What percentage of those who saw the advert bought? Of those who did not see it? And what percentage of the buyers had seen the advert?Saw it, and bought 40 %; Did not see it, and bought 20 %; Buyers who saw it 400/7 ≈ 57.1429 %
    1. Of the 120 who saw it, 48/120=40% bought; of the 180 who did not, 36/180=20% bought. Buying is associated with seeing the advert.
    2. Now the group is the buyers: 48+36=84 of them, 48 of whom saw the advert:
    3. 4884≈57.1%
    4. An association, not proof that the advert worked: people already keen on the product may be the ones who notice its adverts.
  80. 5. Two variables: scatter plots and correlation · Practice problems · ProblemHospital A saves 190 of 200 mild cases and 240 of 400 severe cases. Hospital B saves 360 of 400 mild cases and 110 of 200 severe cases. Find each hospital’s overall survival rate, as a percentage.Hospital A 430/6 ≈ 71.6667 %; Hospital B 470/6 ≈ 78.3333 %
    1. Within each group A does better: 95% against 90% for mild cases, 60% against 55% for severe ones.
    2. Overall, A saves 190+240=430 of its 600 patients and B saves 360+110=470 of its 600:
    3. 430600≈71.7%470600≈78.3%
    4. B looks better overall only because two thirds of its patients were mild cases, while two thirds of A’s were severe: Simpson’s paradox, with severity as the lurking variable.
  81. 5. Two variables: scatter plots and correlation · Practice problems · ProblemFor study time (in hours) and marks, sxy=6 hour-marks, sx=1.5 hours and sy=5 marks. Find r. Then study time is measured in minutes instead: find the new covariance and the new r.r= 0.8; Covariance in minute-marks 360; New r= 0.8
    1. r=61.5×5=0.8
    2. In minutes every x deviation is multiplied by 60, so every product is too: sxy=6×60=360 minute-marks.
    3. But sx becomes 1.5×60=90 minutes as well, so r=36090×5=0.8, unchanged: the 60s cancel.
  82. 6. Probability · Probability puts a number on chance · QuizYou toss a coin twice and record each result. Which is the sample space?B. {HH, HT, TH, TT}Each outcome records both tosses in order, so there are 2×2=4: HH, HT, TH, TT. The number of heads is a summary of the outcome, not the outcome itself, and its three values are not equally likely (one head happens two ways, HT and TH). Listing outcomes so they are equally likely is the key to the next slide.
  83. 6. Probability · Equally likely outcomes: count and divide · QuizTwo fair dice are rolled. What is the probability that the total is 10 or more?A. 1/6Count: a total of 10 happens 3 ways, 11 two ways and 12 one way, so 6 outcomes out of 36, and 6/36=1/6. The tempting 3/11 treats the 11 possible totals as equally likely, which they are not. Count equally likely outcomes, never the possible values of a summary.
  84. 6. Probability · Equally likely outcomes: count and divide · ProblemTwo fair dice are rolled. What is the probability that the total is 8? That both dice show the same number?P(total=8)= 5/36 ≈ 0.138889; P(same number)= 1/6 ≈ 0.166667
    1. A total of 8 happens 5 ways: (2, 6), (3, 5), (4, 4), (5, 3), (6, 2). So P(total=8)=536≈0.139.
    2. The same number happens 6 ways, (1, 1) up to (6, 6), so its chance is 636=16.
  85. 6. Probability · Three rules every probability obeys · QuizA weather model gives tomorrow: sunny 0.5, cloudy 0.3, rainy 0.3, snowy −0.1. Exactly one of the four will happen. What is wrong?B. A probability is negative, breaking the first ruleThey do add up to 0.5+0.3+0.3−0.1=1, which satisfies the second rule, but no probability can be below 0. Checking both, all non-negative and summing to 1 over disjoint outcomes that cover everything, is how you check any probability model, including one a program outputs.
  86. 6. Probability · The complement: one minus the chance · QuizSomeone says: “each roll has a 1/6 chance of a six, so in 6 rolls you are certain to get one.” What is the real chance?B. About 0.671−(5/6)6=1−0.335≈0.665. Adding 1/6 six times counts the outcomes with two or more sixes several times over; the addition rule only works for disjoint events, and “a six on roll 1” and “a six on roll 2” can both happen. The complement avoids the double counting entirely.
  87. 6. Probability · The complement: one minus the chance · ProblemWhat is the probability of at least one head in 5 tosses of a fair coin? Of at least one six in 3 rolls of a fair die?At least one head 31/32 ≈ 0.96875; At least one six 91/216 ≈ 0.421296
    1. The opposite of at least one head is no heads at all: 5 tails, with chance (1/2)5=1/32. So:
    2. P(at least one head)=1−132=3132≈0.969
    3. No six in 3 rolls has chance (5/6)3=125/216, so:
    4. P(at least one six)=1−125216=91216≈0.421
  88. 6. Probability · The addition rule: or · QuizIn a class, 60% of students play a sport, 30% play an instrument, and 20% do both. What share does at least one of the two?B. 70%0.6+0.3−0.2=0.7. The 90% counts the 20% who do both twice, once with the sport players and once with the musicians. A share above 100% is an alarm bell that something was double counted. And the share who do neither is the complement, 1−0.7=30%.
  89. 6. Probability · Independent events multiply · QuizEvents A and B both have probability 0.4, and they are disjoint: they cannot both happen. Are they independent?B. No: if A happens, B becomes impossible, so knowing A changes B’s chanceIndependence needs P(A∩B)=0.4×0.4=0.16, but disjoint means P(A∩B)=0. Knowing A happened tells you B did not: the strongest dependence there is. “Disjoint” and “independent” sound alike and are almost opposites; only events with probability 0 can be both.
  90. 6. Probability · Counting: arrangements and choices · QuizA club of 10 people picks a committee of 3, with no roles. How many different committees are possible?B. 120Order does not matter, so it is (103)=10×9×83×2×1=120. The 720 is 10×9×8, the count if the three had roles (chair, secretary, treasurer), where each committee is counted in its 3!=6 orders. Ask “does swapping two people give a different result?” to decide.
  91. 6. Probability · Try it: choose and the birthday problem · Code challengeFinish choose(n, k): the number of ways to choose k of n things. Return 0 when k < 0 or k > n. Build it up as a product, one factor at a time, rather than computing big factorials.One solution:
    Solution
    long long choose(int n, int k) {  if (k < 0 || k > n) return 0;  long long result = 1;  for (int i = 1; i <= k; i++) {    result = result * (n - k + i) / i;  }  return result;}
    After step i, result is (n−k+ii), always a whole number, so the division is exact at every step, and whole numbers can be compared exactly. The order matters: multiply first, then divide. result * ((n - k + i) / i) would divide two ints first and cut off their fraction. Computing 49! first is a bad idea: it is about 6×1062, far beyond a long long (exact up to about 9.2×1018: 20! fits, 21! does not) and beyond the 253 up to which a double holds whole numbers exactly. Multiplying and dividing as you go keeps the numbers small.
  92. 6. Probability · Try it: choose and the birthday problem · Code challengeFinish sharedBirthday(n): the probability that at least two of n people share a birthday, using the formula above.One solution:
    Solution
    double sharedBirthday(int n) {  double allDifferent = 1;  for (int i = 0; i < n; i++) {    allDifferent *= (365.0 - i) / 365;  }  return 1 - allDifferent;}
    Person i (counting from 0) must avoid the i birthdays already taken, so the factor is (365−i)/365; for i = 365 it is 0, which is why 366 people must share. Write it (365.0 - i) / 365: with (365 - i) / 365 both sides are ints, every factor after the first is 0, and the answer is 1 for any group of two or more. Forgetting the final 1 - returns the chance that everyone is different. The surprise, only 23 people for an even chance, is because there are (232)=253 pairs, each a chance for a match.
  93. 6. Probability · When counting is hard, simulate · Put in orderPut the steps of a Monte Carlo estimate in order.1. Write a function that performs the random experiment once 2. Decide how to tell whether the event happened in one run 3. Repeat the experiment many times, counting the runs where it happened 4. Divide the count by the number of runs 5. Run it again with more runs to see how much the estimate wobblesYou need the experiment and a test for the event before you can repeat them. The estimate is the share of hits. The last step matters: one estimate with no idea of its wobble is a number without its uncertainty, which is exactly what statistics tries to avoid.
  94. 6. Probability · Practice problems · ProblemOne card is drawn from a standard deck of 52. What is the probability that it is red or a face card (a jack, queen or king)? That it is neither?P(red or face)= 8/13 ≈ 0.615385; P(neither)= 5/13 ≈ 0.384615
    1. Red: 26 cards. Face cards: 3 in each of the 4 suits, 12. Red face cards: 6, which are counted in both.
    2. P(red or face)=2652+1252−652=3252=813≈0.615
    3. Neither is the complement: 1−813=513≈0.385. Check: the black cards that are not face cards, ace to 10 in two suits, are 20, and 2052=513.
  95. 6. Probability · Practice problems · ProblemA machine works only if all three of its parts work. The parts work independently, with probabilities 0.9, 0.95 and 0.8. What is the probability that the machine works? That at least one part fails? That all three parts fail?The machine works 0.684; At least one part fails 0.316; All three fail 0.001
    1. P(all work)=0.9×0.95×0.8=0.684
    2. At least one fails is the complement: 1−0.684=0.316.
    3. Each part fails with probability 1−p, and the failures are independent too: 0.1×0.05×0.2=0.001.
  96. 6. Probability · Practice problems · ProblemA door code is 3 letters, each from A to F, and letters may repeat. How many codes are there? How many have three different letters? If a code is chosen at random, what is the chance that its letters are all different?Codes in all 216; All different 120; Probability 5/9 ≈ 0.555556
    1. Each of the 3 positions has 6 choices: 6×6×6=216 codes.
    2. All different: 6 choices for the first letter, 5 for the second, 4 for the third, so 6×5×4=120, the permutations P(6,3).
    3. Every code is equally likely, so the chance is 120216=59≈0.556.
  97. 6. Probability · Practice problems · ProblemA committee of 3 is chosen at random from 6 women and 4 men. How many different committees are possible? How many are all women? What is the probability that the committee is all women?Committees 120; All women 20; Probability 1/6 ≈ 0.166667
    1. Any 3 of the 10 people: (103)=10×9×83×2×1=120 committees.
    2. All women means 3 of the 6 women: (63)=6×5×43×2×1=20.
    3. Every committee is equally likely, so the chance is 20120=16.
  98. 7. Conditional probability and Bayes' theorem · Conditional probability: once you know something · QuizUsing the table, what is P(under 30|coffee)?B. 60/110 ≈ 0.55The condition, “coffee”, is what you know, so the world shrinks to the 110 coffee drinkers, of whom 60 are under 30: 60/110≈0.55. The 0.75 is P(coffee|under 30), the condition the other way round. P(A|B) and P(B|A) are different numbers, and confusing them is the theme of this module.
  99. 7. Conditional probability and Bayes' theorem · Conditional probability: once you know something · ProblemOf 250 students, 120 are in their first year and 130 in their second. 90 of the first-years and 110 of the second-years passed an exam. Find P(passed|first year), P(first year|failed) and P(passed).P(passed|first year)= 0.75; P(first year|failed)= 0.6; P(passed)= 0.8
    1. First-years: 90 passed and 30 failed. Second-years: 110 passed and 20 failed. In all, 200 passed and 50 failed.
    2. Given first year, the world is the 120 first-years: P(passed|first year)=90/120=0.75.
    3. Given failed, it is the 50 who failed, 30 of them first-years: P(first year|failed)=30/50=0.6.
    4. Overall, P(passed)=200/250=0.8. Since 0.75≠0.8, knowing the year changes the chance of passing: they are not independent.
  100. 7. Conditional probability and Bayes' theorem · Chances multiply along a chain · QuizA drawer holds 5 black and 3 white socks. You pull out two without looking. What is the chance both are white?B. 3/2838×27=656=328≈0.107: after one white sock, 2 white remain among 7. The 9/64 is (3/8)2, which treats the draws as independent, as if the first sock were put back. Without replacement, every draw changes the next one’s chances.
  101. 7. Conditional probability and Bayes' theorem · Chances multiply along a chain · ProblemA bag holds 4 red and 6 blue counters. You draw two without putting the first back. What is the probability that both are red? That they are one of each colour?Both red 2/15 ≈ 0.133333; One of each 8/15 ≈ 0.533333
    1. P(both red)=410×39=1290=215
    2. Red then blue: 410×69=2490. Blue then red: 610×49=2490. They are disjoint, so add:
    3. P(one of each)=4890=815≈0.533
    4. Check: both blue is 610×59=13=515, and 215+815+515=1.
  102. 7. Conditional probability and Bayes' theorem · Tree diagrams lay out the chain · QuizFrom the tree, what is the probability that a part is fine and came from machine B?B. 0.38Follow the path: 0.4 for machine B, then 0.95 for fine given B, so 0.4×0.95=0.38. The 0.95 is the chance of fine given B, the branch label, not the whole path. A check: the four path ends, 0.012+0.588+0.020+0.380, add up to 1.
  103. 7. Conditional probability and Bayes' theorem · The law of total probability adds the paths · Code challengeFinish totalProbability(priors, likelihoods): priors[j] is P(Bj) and likelihoods[j] is P(D|Bj). Return P(D).One solution:
    Solution
    #include <vector>
    double totalProbability(const std::vector<double>& priors,                        const std::vector<double>& likelihoods) {  double total = 0;  for (std::size_t j = 0; j < priors.size(); j++) {    total += priors[j] * likelihoods[j];  }  return total;}
    It is the weighted mean from the module on centre: each conditional chance weighted by how likely its piece is. Averaging the likelihoods without weights, (0.02+0.05)/2=0.035, would wrongly treat the machines as equally busy. The priors must add up to 1, since the pieces cover everything.
  104. 7. Conditional probability and Bayes' theorem · Bayes’ theorem turns the condition around · QuizA part is defective. What is the chance it came from machine A?C. 0.375Either directly, 0.6×0.020.032=0.0120.032=0.375, or as the complement of B’s 0.625: a defective part came from exactly one machine. 0.02 is the chance the other way round, P(defective|A), and 0.012 is the path’s chance before you knew the part was defective.
  105. 7. Conditional probability and Bayes' theorem · Ignoring the base rate is the classic mistake · QuizAfter a first positive (posterior about 9.2%), you take a second, independent test with the same rates and it is also positive. Which number is your new prior?B. About 9.2%Yesterday’s posterior is today’s prior: you start from 9.2%, and the second positive lifts it to about 50%. Starting again from 1% would throw away the first test. This chaining is the heart of Bayesian thinking, the subject of a later module. (It assumes the two tests’ errors are independent; if both are fooled by the same thing, the second adds little.)
  106. 7. Conditional probability and Bayes' theorem · Ignoring the base rate is the classic mistake · Code challengeFinish posterior(prior, sensitivity, falsePositive): the probability of the condition after a positive test, by Bayes’ theorem.One solution:
    Solution
    double posterior(double prior, double sensitivity,                 double falsePositive) {  double truePos = sensitivity * prior;  double falsePos = falsePositive * (1 - prior);  return truePos / (truePos + falsePos);}
    The denominator is every positive: true positives from the sick plus false positives from the healthy, the law of total probability. The starter returns the sensitivity, which is exactly base rate neglect. Forgetting 1 - prior in the false positives, and using all people instead of the healthy ones, overcounts the false alarms slightly.
  107. 7. Conditional probability and Bayes' theorem · The prosecutor’s fallacy · QuizWhat is the prosecutor’s fallacy?B. Treating the chance of the evidence given innocence as the chance of innocence given the evidenceIt is base rate neglect in a courtroom: P(E|I) read as P(I|E). The posterior depends on the prior, here how many other people could have been the source, and on the rest of the evidence. A defence lawyer can make the opposite error, saying the match is worthless because 10 others match: the match still narrows millions down to about 11, which is strong evidence combined with anything else.
  108. 7. Conditional probability and Bayes' theorem · The Monty Hall problem · QuizChange the rules: the host does not know where the car is, opens one of the other two doors at random, and it happens to show a goat. Now what is your chance of winning if you switch?B. 1/2Now a goat appearing is evidence. Of the 2/3 of games where the car is behind an unpicked door, a random host reveals it half the time, and those games are thrown out. What remains: “car behind your pick” (1/3) and “car behind the other closed door” (also 1/3), equally likely, so 1/2. The same door, the same goat, a different answer: probability depends on how the information was produced, not just what you saw.
  109. 7. Conditional probability and Bayes' theorem · Practice problems · ProblemA shop buys 50% of its bulbs from supplier A, 30% from B and 20% from C. Of their bulbs, 1%, 3% and 5% are faulty. What share of all the bulbs are faulty? A bulb is faulty: what is the probability that it came from C? From A?P(faulty)= 0.024; P(C|faulty)= 5/12 ≈ 0.416667; P(A|faulty)= 5/24 ≈ 0.208333
    1. P(F)=0.5×0.01+0.3×0.03+0.2×0.05=0.005+0.009+0.010=0.024
    2. P(C|F)=0.0100.024=512≈0.417P(A|F)=0.0050.024=524≈0.208
    3. C supplies only 20% of the bulbs but about 42% of the faulty ones; A supplies half of the bulbs but only about 21% of the faulty ones.
  110. 7. Conditional probability and Bayes' theorem · Practice problems · ProblemA condition affects 2% of people. A test for it is positive for 95% of those who have it, and for 5% of those who do not. Out of 10 000 people tested, how many true positives and how many false positives do you expect? What is P(condition|+)?True positives 190; False positives 490; P(condition|+)= 19/68 ≈ 0.279412
    1. 2% of 10 000 is 200 people with the condition, and 9800 without it.
    2. True positives: 95% of 200 is 190. False positives: 5% of 9800 is 490.
    3. P(condition|+)=190190+490=190680≈0.279
    4. Fewer than 3 in 10 positives have the condition: the healthy 98% produce most of the positives.
  111. 7. Conditional probability and Bayes' theorem · Practice problems · ProblemTake the same test (positive for 95% of people with the condition and 5% without), where 2% have the condition. Someone tests positive, so their chance is now 1968, and then takes a second, independent test, also positive. What is their chance of having the condition now? And for someone who tests negative once, what is the chance they do not have it?After two positives 361/410 ≈ 0.880488; P(no condition|−)= 931/932 ≈ 0.998927
    1. Start from the prior 1968, so 4968 do not have the condition. The $\frac{1}{68}$s cancel:
    2. 0.95×190.95×19+0.05×49=18.0518.05+2.45=18.0520.5=361410≈0.880
    3. For one negative, in 10 000 people: 95% of the 9800 without the condition test negative, 9310, and so do 5% of the 200 with it, 10:
    4. P(no condition|−)=93109310+10=931932≈0.9989
    5. A second positive lifts the chance from about 28% to 88%. A negative is very reassuring, because the condition was rare to begin with.
  112. 7. Conditional probability and Bayes' theorem · Practice problems · ProblemThe chance of rain today is 0.3. If it rains today, the chance of rain tomorrow is 0.6; if it does not, the chance is 0.2. What is the probability that it rains on both days? That it rains tomorrow? If it rains tomorrow, what is the probability that it also rained today?Rain on both days 0.18; Rain tomorrow 0.32; P(rain today|rain tomorrow)= 0.5625
    1. Both days: 0.3×0.6=0.18.
    2. Rain tomorrow follows a wet day or a dry one: 0.3×0.6+0.7×0.2=0.18+0.14=0.32.
    3. P(rain today|rain tomorrow)=0.180.32=0.5625
    4. Knowing tomorrow is wet raises the chance that today was wet from 0.3 to about 0.56: the two days are not independent.
  113. 8. Random variables and expected value · A probability mass function lists the chances · QuizA random variable Y takes the values 1, 2 and 3 with P(Y=1)=0.2 and P(Y=2)=0.5. What is P(Y=3), and P(Y≥2)?A. 0.3 and 0.8The chances must add up to 1, so P(Y=3)=1−0.2−0.5=0.3. Then P(Y≥2)=P(Y=2)+P(Y=3)=0.8, or by the complement, 1−P(Y=1)=0.8. The values are disjoint events, so adding their chances is allowed.
  114. 8. Random variables and expected value · A probability mass function lists the chances · ProblemThe number of children X in a household takes the values 0, 1, 2, 3 and 4 with probabilities 0.2, 0.3, 0.25, k and 0.1. Find k and P(X≥2).k= 0.15; P(X≥2)= 0.5
    1. k=1−(0.2+0.3+0.25+0.1)=1−0.85=0.15.
    2. P(X≥2)=0.25+0.15+0.1=0.5, or by the complement, 1−0.2−0.3=0.5.
  115. 8. Random variables and expected value · The expected value is the long-run average · QuizA café sells 0, 1 or 2 cakes an hour with probabilities 0.3, 0.5 and 0.2. How many cakes does it expect to sell in an 8-hour day?B. 7.2Per hour, E[X]=0×0.3+1×0.5+2×0.2=0.9 cakes, and expected values add up over hours (a later slide), so 8×0.9=7.2. The answer 1 is the most likely value, the mode, not the expected value. A shop orders stock by the expected value plus a margin for the spread.
  116. 8. Random variables and expected value · The variance of a random variable · ProblemThe number of children X in a household is 0, 1, 2, 3 or 4, with probabilities 0.2, 0.3, 0.25, 0.15 and 0.1. Find E[X], Var⁡(X) and the standard deviation σ.E[X]= 1.65; Var⁡(X)= 1.5275; σ= sqrt(1.5275) ≈ 1.23592
    1. E[X]=0×0.2+1×0.3+2×0.25+3×0.15+4×0.1=1.65
    2. E[X2]=0×0.2+1×0.3+4×0.25+9×0.15+16×0.1=4.25
    3. Var⁡(X)=4.25−1.652=4.25−2.7225=1.5275σ=1.5275≈1.236
    4. So a household has 1.65 children on average, give or take about 1.2.
  117. 8. Random variables and expected value · Try it: the mean and variance of a distribution · Code challengeFinish expectedValue(values, probs): probs[i] is the probability of values[i]. Return the sum of each value times its probability.One solution:
    Solution
    #include <vector>
    double expectedValue(const std::vector<double>& values,                     const std::vector<double>& probs) {  double total = 0;  for (std::size_t i = 0; i < values.size(); i++) {    total += values[i] * probs[i];  }  return total;}
    It is a weighted mean whose weights already add up to 1, so there is no division. Dividing by values.size() as for a plain mean would only be right if every value were equally likely, and then the probabilities would be 1/n anyway. The tests write the probabilities as 1.0 / 8, not 1 / 8: between two ints that is 0.
  118. 8. Random variables and expected value · Try it: the mean and variance of a distribution · Find the bugThis variance gives about −2.92 for a fair die. Which line is wrong?Line 8: return meanOfSquares - mean * mean;The shortcut is E[X2]−μ2, the mean of the squares minus the square of the mean. Written the other way round it is the right size with the wrong sign: 12.25−15.17≈−2.92. A negative variance is impossible, since it is an average of squares: a quick sanity check for any spread you compute.
  119. 8. Random variables and expected value · Try it: the mean and variance of a distribution · Code challengeFinish variance(values, probs): the variance of the distribution, using E[(X−μ)2] or the shortcut.One solution:
    Solution
    #include <vector>
    double variance(const std::vector<double>& values,                const std::vector<double>& probs) {  double mean = 0;  for (std::size_t i = 0; i < values.size(); i++) {    mean += values[i] * probs[i];  }  double total = 0;  for (std::size_t i = 0; i < values.size(); i++) {    double d = values[i] - mean;    total += d * d * probs[i];  }  return total;}
    Find the mean first, then weight each squared distance by its probability. For heads in 3 tosses: (0−1.5)2⋅18+(1−1.5)2⋅38+(2−1.5)2⋅38+(3−1.5)2⋅18=0.75. The two-pass version is also better numerically: the shortcut subtracts two big, nearly equal numbers when the mean is large, losing precision.
  120. 8. Random variables and expected value · Shifting and scaling a random variable · QuizA shop’s daily profit X has mean 200 and variance 900 (in coins). Each day 50 coins of rent are paid, and the owner keeps half of what is left: Y=(X−50)/2. What are the mean and SD of Y?A. 75 and 15E[Y]=(200−50)/2=75. The SD of X is 900=30; subtracting 50 leaves it alone and halving halves it, so 15. The 225 is the new variance, 900/4. Working with SDs is easier: they scale like the data, while variances scale by the square.
  121. 8. Random variables and expected value · Expected values always add · QuizYou roll 10 dice. What is the expected number of sixes?B. 10/6 ≈ 1.67Let Xi=1 if die i shows a six: E[Xi]=1/6. By linearity, the expected count is 10×16≈1.67. No need for the distribution of the count (that is the binomial, next module). Indicator variables plus linearity solve problems that look hopeless any other way.
  122. 8. Random variables and expected value · Variances add for independent variables · QuizTwo independent machines fill bags: one with SD 3 g, the other with SD 4 g. What is the SD of the difference between a bag from each?B. 5 gVariances add, even for a difference: 32+42=25, so the SD is 25=5 g. The tempting 1 g subtracts the SDs, as if the errors cancelled; they are independent, so they are just as likely to pile up. 7 g adds SDs, which is only right if the two always err together. 25 is the variance.
  123. 8. Random variables and expected value · Games and fair bets · QuizA game: roll a die, and you are paid as many coins as the number shown. What is the fair price to play?B. 3.5 coinsThe payout’s expected value is 3.5 coins, so paying 3.5 makes your net expected winnings 0: fair. At 3 coins you gain 0.5 per game on average; at 4 you lose 0.5. The fair price of any gamble is its expected payout, which is how insurers and lotteries start their pricing, before adding their own edge.
  124. 8. Random variables and expected value · Expected value is not the whole story · QuizA lottery ticket costs 2 coins and its expected payout is 0.9 coins. Which statement is right?B. Over very many tickets, buyers get back about 45% of what they spendThe expected value is a long-run average: per ticket, 0.9/2=45% comes back, and the expected net is −1.1 coins. Almost every single ticket pays 0; a rare few pay a lot. Buying more tickets multiplies the expected loss: linearity of expectation says 10 tickets expect to lose 11 coins.
  125. 8. Random variables and expected value · Practice problems · ProblemA random variable X has mean 12 and standard deviation 3. Let Y=5X−20. Find E[Y], the standard deviation of Y, and Var⁡(Y).E[Y]= 40; σY= 15; Var⁡(Y)= 225
    1. E[Y]=5×12−20=40.
    2. σY=|5|×3=15, and Var⁡(Y)=52×32=225, which is 152.
  126. 8. Random variables and expected value · Practice problems · ProblemA gift box holds 4 jars of jam. Each jar’s mass has mean 150 g and SD 6 g, independently of the others, and the empty box weighs exactly 80 g. Find the mean and the SD of the full box’s mass. Then find the SD of the difference in mass between two single jars.Mean of the full box 680 g; SD of the full box 12 g; SD of the difference sqrt(72) ≈ 8.48528 g
    1. Mean: 4×150+80=680 g.
    2. Variance: 4×62=144 g2, and the box adds none. So the SD is 144=12 g, not 4×6=24 g.
    3. For the difference of two jars, the variances add again: 36+36=72, so the SD is 72≈8.49 g.
  127. 8. Random variables and expected value · Practice problems · ProblemA game costs 4 coins. You roll a fair die: a 6 pays 12 coins, a 4 or a 5 pays 3 coins, and anything else pays nothing. Find the expected payout, your expected net winnings per game, and the fair price to play.Expected payout 3 coins; Expected net winnings -1 coins; Fair price 3 coins
    1. E[payout]=12×16+3×26+0×36=2+1=3 coins
    2. You pay 4, so the expected net winnings are 3−4=−1 coin a game.
    3. A fair price makes the expected net winnings 0, so it is the expected payout: 3 coins.
  128. 8. Random variables and expected value · Practice problems · ProblemA quiz has 12 questions, each with 4 options, and you guess every answer at random. What is the expected number of right answers? If each right answer scores +1 and each wrong one −13, what is your expected score?Expected number right 3; Expected score 0
    1. Each question is right with probability 14, so by linearity the expected number right is 12×14=3.
    2. One question’s expected score:
    3. (+1)×14+(−13)×34=14−14=0
    4. So the expected total is 12×0=0: the penalty is set so that blind guessing gains nothing on average.
  129. 9. Binomial, geometric and Poisson · A Bernoulli trial: success or failure · QuizA website visitor buys something with probability 0.1. What is the SD of the Bernoulli variable “buys”?C. 0.3The variance is p(1−p)=0.1×0.9=0.09, and the SD is its square root, 0.3. 0.09 is the variance, not the SD. The SD of a 0-or-1 variable is large compared with its mean of 0.1, which is why measuring a small rate precisely takes many visitors.
  130. 9. Binomial, geometric and Poisson · The binomial counts successes in n trials · QuizWhich of these counts are binomial?A. The number of sixes in 12 rolls of a die; D. The number of 20 randomly chosen voters, from a country of millions, who support a policyTwelve rolls: binary (six or not), independent, fixed n=12, same p=1/6. The voters are drawn without replacement, but from millions, so each draw barely changes the chances: binomial is an excellent model. The rolls until a six has no fixed n (that is the geometric, later). The cards are drawn without replacement from just 52, so the chance of an ace changes noticeably after each card: not binomial.
  131. 9. Binomial, geometric and Poisson · The binomial formula · QuizA fair coin is tossed 10 times. Which is P(at most 2 heads)?B. [(100)+(101)+(102)](0.5)10≈0.055“At most 2” is 0, 1 or 2 heads, disjoint events, so add their chances: (1+10+45)/1024=56/1024≈0.055. With p=0.5, every sequence has probability (0.5)10, so only the counts of sequences differ. The first option is “exactly 2”. Adding up the pmf up to k gives the cumulative distribution function, P(X≤k).
  132. 9. Binomial, geometric and Poisson · The binomial formula · ProblemEach seed sprouts with probability 0.8, independently of the others. You plant 6. What is the probability that exactly 5 sprout? That all 6 sprout? That at least 5 sprout?P(X=5)= 6*0.8^5*0.2 ≈ 0.393216; P(X=6)= 0.8^6 ≈ 0.262144; P(X≥5)= 6*0.8^5*0.2 + 0.8^6 ≈ 0.65536
    1. P(X=5)=(65)(0.8)5(0.2)1=6×0.32768×0.2≈0.393
    2. P(X=6)=(66)(0.8)6(0.2)0=0.86≈0.262
    3. The two are disjoint, so P(X≥5)≈0.393+0.262=0.655.
  133. 9. Binomial, geometric and Poisson · Mean np, variance np(1 − p) · QuizA basketball player makes 80% of free throws, independently. In 10 throws, what are the mean and SD of the number made?B. 8 and about 1.26np=10×0.8=8, and the variance is np(1−p)=10×0.8×0.2=1.6, so the SD is 1.6≈1.26. 1.6 is the variance. Making 6 or fewer would be about 1.6 SDs below the mean: unusual but not shocking, which matters before calling a player “in a slump”.
  134. 9. Binomial, geometric and Poisson · Try it: the binomial pmf and cdf · Code challengeFinish binomialPmf(n, k, p): the chance of exactly k successes in n trials. A choose function is given.One solution:
    Solution
    #include <cmath>
    double choose(int n, int k) {  if (k < 0 || k > n) return 0;  double r = 1;  for (int i = 1; i <= k; i++) r = r * (n - k + i) / i;  return r;}
    double binomialPmf(int n, int k, double p) {  return choose(n, k) * std::pow(p, k) * std::pow(1 - p, n - k);}
    Three factors: the number of sequences, the chance of the k successes, and the chance of the n−k failures. Forgetting (nk) gives the chance of one particular sequence, such as SSFFF, which is 10 times too small here. std::pow(p, k) is pk: C++ has no power operator, and p ^ k is not one (it does not even compile on a double). The “adds up to 1” test is a good habit for any pmf you code.
  135. 9. Binomial, geometric and Poisson · Try it: the binomial pmf and cdf · Code challengeFinish binomialCdf(n, k, p): the chance of at most k successes, P(X≤k). binomialPmf is given.One solution:
    Solution
    #include <algorithm>#include <cmath>
    double binomialPmf(int n, int k, double p) {  double c = 1;  for (int i = 1; i <= k; i++) c = c * (n - k + i) / i;  return c * std::pow(p, k) * std::pow(1 - p, n - k);}
    double binomialCdf(int n, int k, double p) {  double total = 0;  for (int j = 0; j <= std::min(k, n); j++) {    total += binomialPmf(n, j, p);  }  return total;}
    Add the pmf from 0 up to and including k: the loop’s <= matters, since < would leave out exactly k. For “at least k”, use the complement, 1−P(X≤k−1): an easy off-by-one to get wrong, so write down which values are in the event before coding it.
  136. 9. Binomial, geometric and Poisson · The geometric distribution: waiting for a success · QuizYou have rolled a die 10 times without a six. What is the expected number of further rolls until the first six?A. 6The rolls are independent, so the past does not matter: the wait starts again, with mean 6. The geometric is memoryless: P(X>j+k|X>j)=P(X>k). “Overdue” is the gambler’s fallacy again. Memorylessness is a strong assumption: a light bulb that has burned for years is more likely to fail soon, so its lifetime is not geometric.
  137. 9. Binomial, geometric and Poisson · The Poisson distribution counts rare events · QuizA help desk gets on average 3 calls a minute. What is the chance of a minute with no calls?B. About 0.05P(X=0)=30e−30!=e−3≈0.0498. About one minute in 20 is quiet. 0.22 is P(X=2). The rate scales with the interval: in half a minute, λ=1.5; in an hour, λ=180. Getting the interval and the rate to match is the first step of any Poisson problem.
  138. 9. Binomial, geometric and Poisson · The Poisson distribution counts rare events · ProblemA shop gets 4 complaints a week on average, at random and independently. What is the probability of exactly 2 complaints in a week? Of no complaints in half a week?2 in a week 8*exp(-4) ≈ 0.146525; None in half a week exp(-2) ≈ 0.135335
    1. P(X=2)=42e−42!=8e−4≈0.147
    2. In half a week, λ=2:
    3. P(X=0)=20e−20!=e−2≈0.135
  139. 9. Binomial, geometric and Poisson · The Poisson is the binomial for rare events · QuizA chip has a 1 in 1000 chance of a defect, independently. In a batch of 2000 chips, what is the Poisson approximation to the chance that none are defective?A. e−2≈0.135λ=np=2000×0.001=2, and P(X=0)=e−2≈0.1353. The exact binomial, 0.9992000≈0.1352, agrees to three decimal places. 2e−2 is the chance of exactly one defect. With (2000k) in the exact formula, the Poisson is also much easier to compute.
  140. 9. Binomial, geometric and Poisson · Try it: the Poisson pmf · Code challengeFinish poissonPmf(k, lambda): λke−λ/k!. Build the terms up in a loop, rather than computing λk and k! separately, so large k does not overflow.One solution:
    Solution
    #include <cmath>
    double poissonPmf(int k, double lambda) {  double term = std::exp(-lambda);  for (int i = 1; i <= k; i++) term *= lambda / i;  return term;}
    Each term is the previous one times λ/k: P(X=k)=P(X=k−1)⋅λk. Computing std::pow(180, 200) directly gives inf (too big for a double) and 200! does too, so their ratio is inf / inf, which is nan, though the answer is an ordinary 0.0097. Watch out for one more trap: e−λ itself underflows to 0 for λ above about 745, and then statisticians work with logarithms of probabilities instead.
  141. 9. Binomial, geometric and Poisson · Which distribution fits · QuizA quality inspector tests bulbs from a production line, one after another, until she finds the first faulty one. Which distribution models the number of bulbs tested?B. GeometricThe number of trials is not fixed; it is what is being counted, up to and including the first “success” (a faulty bulb). That is geometric. Binomial needs a fixed number of bulbs, such as “how many of 50 are faulty”. Poisson counts events in a fixed interval of time or space, with no trials at all.
  142. 9. Binomial, geometric and Poisson · Practice problems · ProblemA test has 20 multiple-choice questions with 5 options each, and a student guesses every answer. Find the mean and the SD of the number of right answers, and the probability of getting none right.Mean 4; SD sqrt(3.2) ≈ 1.78885; P(X=0)= 0.8^20 ≈ 0.0115292
    1. The number right is X∼B(20,0.2), with mean np=20×0.2=4.
    2. Its variance is np(1−p)=20×0.2×0.8=3.2, so its SD is 3.2≈1.79.
    3. P(X=0)=(200)(0.2)0(0.8)20=0.820≈0.0115
  143. 9. Binomial, geometric and Poisson · Practice problems · ProblemAt a fair, each throw lands a ring on the peg with probability 0.25, independently. What is the probability that the first success comes on the 3rd throw? That you need more than 4 throws? What is the expected number of throws up to and including the first success?P(X=3)= 9/64 ≈ 0.140625; P(X>4)= 81/256 ≈ 0.316406; E[X]= 4
    1. P(X=3)=(0.75)2×0.25=964≈0.141
    2. P(X>4)=(0.75)4=81256≈0.316
    3. E[X]=1/p=1/0.25=4 throws.
  144. 9. Binomial, geometric and Poisson · Practice problems · ProblemEach letter a firm sends has a 1 in 500 chance of being lost, independently. It sends 1500 letters. Using the Poisson approximation, what is the probability that none are lost? That at most one is lost?None lost exp(-3) ≈ 0.0497871; At most one lost 4*exp(-3) ≈ 0.199148
    1. λ=1500×1500=3.
    2. P(X=0)=e−3≈0.0498P(X=1)=31e−31!=3e−3≈0.149
    3. P(X≤1)=e−3+3e−3=4e−3≈0.199. The exact binomial gives 0.0496 and 0.199: very close.
  145. 9. Binomial, geometric and Poisson · Practice problems · ProblemA machine makes 10% defective items, independently. In a sample of 10 items, what is the probability of no defective items? Of exactly one? Of at least two?P(X=0)= 0.9^10 ≈ 0.348678; P(X=1)= 0.9^9 ≈ 0.38742; P(X≥2)= 1 - 0.9^10 - 0.9^9 ≈ 0.263901
    1. P(X=0)=0.910≈0.349
    2. P(X=1)=(101)(0.1)(0.9)9=0.99≈0.387
    3. The complement of “at least two” is “0 or 1”:
    4. P(X≥2)=1−0.349−0.387≈0.264
  146. 10. Continuous distributions and the normal curve · For continuous variables, probability is area · QuizA density curve has height 1.5 at x=2. What does that mean?B. Values near 2 are relatively likely: the chance of a small interval around 2 is about 1.5 times its widthA density is not a probability: it is probability per unit of x, so it can exceed 1 as long as the total area is 1. The chance of landing in [2,2.01] is about 1.5×0.01=0.015. And P(X=2) is exactly 0 for any continuous variable, which is also why ≤ and < give the same probabilities.
  147. 10. Continuous distributions and the normal curve · The uniform distribution: flat · QuizFor the bus wait, uniform on [0,10] minutes, what are the mean and the SD?A. 5 and about 2.89The mean is the midpoint, (0+10)/2=5. The variance is 102/12≈8.33, so the SD is 8.33≈2.89 minutes. 8.33 is the variance. std::uniform_real_distribution<double>(0.0, 1.0) gives numbers uniform on [0,1), with mean 0.5 and SD 1/12≈0.289, which is the raw material for simulating every other distribution.
  148. 10. Continuous distributions and the normal curve · The uniform distribution: flat · ProblemA train comes every 15 minutes and you arrive at a random moment, so your wait is uniform on [0,15] minutes. What is the probability that you wait more than 10 minutes? What are the mean and the SD of the wait?P(wait>10)= 1/3 ≈ 0.333333; Mean 7.5 min; SD 15/sqrt(12) ≈ 4.33013 min
    1. The density is 115 on [0,15]. The area from 10 to 15 is a rectangle: 5×115=13.
    2. The mean is the midpoint, 0+152=7.5 minutes.
    3. σ=15212=1512≈4.33 minutes
  149. 10. Continuous distributions and the normal curve · The exponential distribution: waiting for the next event · QuizCustomers arrive at a rate of 2 per minute (a Poisson process). What is the chance the gap between two customers is more than 1 minute?A. e−2≈0.135P(X>t)=e−λt=e−2×1≈0.135. Equivalently, the gap is longer than a minute exactly when a minute passes with no arrivals, a Poisson count of 0 with mean 2: e−2 again. 1−e−2 is the chance the gap is shorter. The two views, counts per interval and gaps between events, describe the same random process.
  150. 10. Continuous distributions and the normal curve · The standard normal and its table · QuizThe table only lists positive z. How do you find Φ(−1)?B. 1−Φ(1)=0.1587The curve is symmetric about 0, so the area left of −1 equals the area right of +1, which is 1−Φ(1)≈0.1587. A probability is never negative. 0.3413 is the area between 0 and 1. Sketching the curve and shading the area you want is the surest way through any normal calculation.
  151. 10. Continuous distributions and the normal curve · Normal calculations: standardise, then look up · QuizExam marks are normal with mean 60 and SD 12. A grade A goes to marks above 84. About what share of students get an A?A. 2.3%z=84−6012=2, and P(Z>2)=1−Φ(2)=1−0.9772=0.0228, about 2.3%. 97.7% is the share below 84: always check which side of the cut-off the question wants. The empirical rule gives the same estimate: 95% within 2 SDs, so 2.5% above.
  152. 10. Continuous distributions and the normal curve · Normal calculations: standardise, then look up · ProblemBottles are filled with a volume that is normal with mean 500 ml and SD 4 ml. Using the table of Φ, what share of bottles (as a decimal) hold less than 508 ml? Between 498 and 504 ml? Above what volume are the fullest 5% of bottles?Below 508 ml 0.9772; 498 to 504 ml 0.5328; The fullest 5% are above 506.58 ml
    1. 508 ml is z=508−5004=2, so P(X<508)=Φ(2)≈0.9772.
    2. 498 ml is z=−0.5 and 504 ml is z=1:
    3. Φ(1)−Φ(−0.5)=0.8413−(1−0.6915)=0.8413−0.3085=0.5328
    4. The fullest 5% are above the 95th percentile, and Φ(1.645)=0.95:
    5. x=500+1.645×4≈506.6 ml
  153. 10. Continuous distributions and the normal curve · Try it: normal probabilities in code · Code challengeFinish normalBetween(a, b, mu, sigma): the probability that a normal variable with mean mu and SD sigma lands between a and b. phi(z), the standard normal cdf, is given.One solution:
    Solution
    #include <cmath>
    // The standard normal cdf, from <cmath>'s error function.double phi(double z) {  return 0.5 * (1 + std::erf(z / std::sqrt(2.0)));}
    double normalBetween(double a, double b, double mu, double sigma) {  return phi((b - mu) / sigma) - phi((a - mu) / sigma);}
    Standardise both ends with the same mu and sigma, then subtract the two areas: everything left of b minus everything left of a. The starter forgets to standardise, which happens to work for the standard normal, so the first test passes and the others do not. -INFINITY (from <cmath>) works because phi of it is 0, a nice way to write “below 180”. phi is one line because <cmath> has the error function, std::erf, and Φ(z)=12(1+erf⁡(z/2)).
  154. 10. Continuous distributions and the normal curve · Try it: normal probabilities in code · Code challengeFinish area(f, a, b, n): approximate the area under f from a to b with the trapezoid rule: split the interval into n equal strips of width h, and add up h * (f(left) + f(right)) / 2 for each strip.One solution:
    Solution
    #include <functional>
    double area(const std::function<double(double)>& f,            double a, double b, int n) {  double h = (b - a) / n;  double total = 0;  for (int i = 0; i < n; i++) {    double left = a + i * h;    total += h * (f(left) + f(left + h)) / 2;  }  return total;}
    Each strip is a trapezoid: its width h times the mean of its two side heights. With 1000 strips the error is tiny, about h2 times the curve’s bendiness. This is how you check a cdf formula, or compute a probability for a density nobody has tabulated. Computing left from a + i * h each time, rather than adding h repeatedly, avoids piling up rounding errors. f is a std::function<double(double)>, any function from a double to a double: the tests pass a named function, normalPdf, and lambdas such as [](double x) { return 0.5 * std::exp(-0.5 * x); }.
  155. 10. Continuous distributions and the normal curve · The normal approximation to the binomial · QuizWith the continuity correction, which normal probability approximates P(X≥60) for X∼B(100,0.5)?B. P(Y≥59.5)The event includes 60, whose interval is [59.5,60.5], so the area starts at 59.5. Starting at 60.5 would leave out k=60 itself. Ask “which whole numbers are in the event?”, then widen by half a unit at each end. Here P(Y≥59.5)=1−Φ(1.9)≈0.029.
  156. 10. Continuous distributions and the normal curve · Checking normality with a QQ plot · QuizIn a QQ plot, the points follow the line in the middle, but at the right end they rise far above it, and at the left end they sit above it too, bunched up. What does that suggest?B. The data is skewed right: a long upper tail and a short lower oneThe largest values are much bigger than a normal sample would give, a long right tail, and the smallest are not as small as normal ones would be, a short left tail: right skew, like the exponential above. A plot that bends below the line on the left and above it on the right (an S-shape) signals heavy tails in both directions instead. In practice, small wiggles are normal; look for clear bends.
  157. 10. Continuous distributions and the normal curve · Practice problems · ProblemCalls reach a help line at random, at a rate of 4 an hour. What is the probability of waiting more than 30 minutes for the next call? What is the mean wait, in minutes? What is the probability that the next call comes within 15 minutes?Wait over 30 minutes exp(-2) ≈ 0.135335; Mean wait 15 min; Within 15 minutes 1 - exp(-1) ≈ 0.632121
    1. P(X>0.5)=e−4×0.5=e−2≈0.135
    2. The mean wait is 1/λ=1/4 of an hour: 15 minutes.
    3. P(X<0.25)=1−e−4×0.25=1−e−1≈0.632
    4. More than half of the waits are shorter than the mean: the exponential is skewed right, with a long tail of long waits.
  158. 10. Continuous distributions and the normal curve · Practice problems · ProblemTest scores are normal with mean 100 and SD 15. Above what score are the top 2.5%? What share of people (as a decimal) score above 130? Between 85 and 115?The top 2.5% score above 129.4; Above 130 0.0228; 85 to 115 0.6826
    1. The top 2.5% lie above the z with Φ(z)=0.975, which is 1.96: x=100+1.96×15=129.4.
    2. 130 is z=130−10015=2, so P(Z>2)=1−0.9772=0.0228.
    3. 85 and 115 are z=−1 and z=1: Φ(1)−Φ(−1)=0.8413−0.1587=0.6826, the 68% of the empirical rule.
  159. 10. Continuous distributions and the normal curve · Practice problems · ProblemA fair coin is tossed 100 times. Using the normal approximation with the continuity correction, find the probability of at most 52 heads, and of between 48 and 52 heads (both included).P(X≤52)≈ 0.6915; P(48≤X≤52)≈ 0.383
    1. μ=100×0.5=50 and σ=100×0.5×0.5=5.
    2. P(X≤52)≈Φ(52.5−505)=Φ(0.5)≈0.6915
    3. From 48 to 52 heads, both included, the area runs from 47.5 to 52.5, which is z=−0.5 to z=0.5:
    4. Φ(0.5)−Φ(−0.5)=0.6915−0.3085=0.3830
    5. The exact binomial answers are 0.6914 and 0.3827: very close.
  160. 10. Continuous distributions and the normal curve · Practice problems · ProblemA random variable X has the density f(x)=x2 for 0≤x≤2, and 0 elsewhere: a triangle. Find P(X≤1), P(X>1.5), and the median m, the value with P(X≤m)=0.5.P(X≤1)= 1/4 ≈ 0.25; P(X>1.5)= 0.4375; m= sqrt(2) ≈ 1.41421
    1. The whole triangle has base 2 and height f(2)=1, so its area is 12×2×1=1, as a density’s must be.
    2. The area from 0 to a is a smaller triangle, with base a and height a2: P(X≤a)=a24.
    3. P(X≤1)=14, and P(X>1.5)=1−1.524=1−0.5625=0.4375.
    4. For the median, m24=0.5, so m2=2 and m=2≈1.414: above the middle of the range, 1, because more of the area is on the right.
  161. 11. Sampling and the central limit theorem · You study a sample to learn about a population · QuizA school has 2000 pupils. You pick 50 of them and find their mean exam score is 68. Which is the parameter?B. The mean score of all 2000 pupilsA parameter belongs to the population: the mean of all 2000 pupils, which you don’t know. The 68 is a statistic, x‾, computed from the sample; a different 50 pupils would give a different number. Mixing up the two is the root of most confusion in this module.
  162. 11. Sampling and the central limit theorem · Random sampling gives every member a fair chance · QuizA city picks 12 of its 300 bus routes at random and surveys every passenger on those 12 routes one morning. What design is this?C. Cluster sampleThe routes are clusters: ready-made groups, chosen at random, with everyone inside measured. A stratified sample would instead take some passengers from every route. Clusters are cheap, but passengers on the same route are alike, so 12 routes tell you less than the same number of passengers spread over all 300.
  163. 11. Sampling and the central limit theorem · A biased method misses the same way every time · QuizA magazine asks readers to mail in their opinion and gets 50 000 replies. A pollster asks 1000 people chosen at random. Which estimate of national opinion should you trust more?B. The pollster: a random sample avoids the bias of self-selectionReaders who choose to reply differ from everyone else, and 50 000 of them only pins down their opinion precisely. In 1936 the Literary Digest mailed 10 million ballots, got 2.4 million back, and predicted the wrong US president; George Gallup’s far smaller but more carefully chosen sample got it right. Randomness beats size when the method is biased.
  164. 11. Sampling and the central limit theorem · A statistic has a distribution of its own · QuizWhat is the mean of this sampling distribution, the average of all 36 possible two-roll means?B. 3.5The distribution is symmetric about 3.5, so its mean is 3.5, the population mean. This is true in general: the mean of the sampling distribution of x‾ is μ. That is what it means to say x‾ is an unbiased estimator. One sample can miss; on average it doesn’t.
  165. 11. Sampling and the central limit theorem · The standard error measures how much a statistic wobbles · Fill the blanksComplete the standard error of a mean, given the population standard deviation sigma and sample size n.1: sqrt, 2: nThe SE divides by the square root of n, not by n. That is why precision is expensive: to halve the SE you need four times the data, and to cut it to a tenth you need a hundred times.
  166. 11. Sampling and the central limit theorem · The standard error measures how much a statistic wobbles · ProblemResting heart rates of adults have a standard deviation of σ=12 beats per minute. What is the standard error of the mean of a random sample of 16 adults? How many adults would you need for a standard error of 1.5 beats per minute?SE with n=16 3 beats per minute; Sample size for an SE of 1.5 64 adults
    1. Divide the spread of single values by the square root of the sample size:
    2. SE=σn=1216=124=3 beats per minute
    3. For a standard error of 1.5, solve for n:
    4. 12n=1.5n=121.5=8n=64
    5. Halving the standard error, from 3 to 1.5, takes four times the data: 64 adults instead of 16.
  167. 11. Sampling and the central limit theorem · The law of large numbers: averages settle down · QuizA fair coin has come up heads 8 times in a row. By the law of large numbers, what is the chance the next flip is tails?B. Exactly 1/2The coin has no memory: each flip is still 1/2. The law of large numbers does not work by correcting past results; it works by swamping them. Eight extra heads matter a lot after 10 flips and almost nothing after 10 000. Believing tails is “due” is the gambler’s fallacy.
  168. 11. Sampling and the central limit theorem · The law of large numbers: averages settle down · Code challengeWrite runningMeans(xs), which returns the mean of the first 1, 2, 3, … values of xs, so you can watch an average settle down. For {4, 2, 6, 0} it returns {4, 3, 4, 3}.One solution:
    Solution
    #include <vector>
    std::vector<double> runningMeans(const std::vector<double>& xs) {  std::vector<double> means;  double total = 0;  for (int i = 0; i < xs.size(); i++) {    total += xs[i];    means.push_back(total / (i + 1));  }  return means;}
    A running total makes this one pass: after adding the k-th value, divide by k (that is i + 1, since vectors count from 0). Recomputing each mean from scratch also works but does n2/2 additions. The usual slip is dividing by i, which is off by one and divides by zero on the first value (4.0 / 0 is inf).
  169. 11. Sampling and the central limit theorem · The central limit theorem: means become normal · QuizYou take one sample of 100 waits from this skewed population. What does the CLT say is roughly normal?C. The distribution of x‾ over many possible samples of 100The CLT is about the sampling distribution of the mean, not about the data. Your 100 waits still look skewed, like the population they came from. It is their average that would vary in a bell shape if you repeated the sampling. Expecting the data themselves to turn normal is the classic misreading.
  170. 11. Sampling and the central limit theorem · The central limit theorem: means become normal · ProblemCoffee-shop waits are skewed, with mean μ=2 minutes and σ=2 minutes. You time a random sample of 64 customers. What is the standard error of their mean wait, and roughly what is the probability that the mean wait is more than 2.5 minutes? Use Φ(2)=0.9772.SE 0.25 min; P(x‾>2.5) 0.0228
    1. The standard error of the mean:
    2. SE=σn=264=28=0.25 min
    3. By the central limit theorem, x‾ is approximately N(2, 0.252), even though single waits are skewed. Standardise 2.5:
    4. z=2.5−20.25=2P(x‾>2.5)≈P(Z>2)=1−Φ(2)=1−0.9772=0.0228
    5. A single wait over 2.5 minutes is common (with the skewed waits of the graph, about 29% of customers wait that long), but a mean of 64 waits above 2.5 happens only about 2% of the time.
  171. 11. Sampling and the central limit theorem · Simulating a sampling distribution · Put in orderPut the steps of simulating the sampling distribution of a mean in order.1. Choose a population to draw from and a sample size n 2. Draw a random sample of n values 3. Work out the sample mean and keep it 4. Repeat the draw-and-average many thousands of times 5. Summarise the kept means: their average, SD and shapeEach repetition makes one sample mean; the sampling distribution only appears once you have thousands of them. A common mistake is to draw one huge sample and look at its histogram: that shows the population’s shape, not how the mean varies.
  172. 11. Sampling and the central limit theorem · Simulating a sampling distribution · Code challengeIn practice you don’t know σ, so you estimate the SE from the sample: SE=s/n, where s is the sample standard deviation (dividing by n−1). Write standardError(xs).One solution:
    Solution
    #include <cmath>#include <vector>
    double standardError(const std::vector<double>& xs) {  int n = xs.size();  double mean = 0;  for (double x : xs) mean += x;  mean /= n;  double ss = 0;  for (double x : xs) ss += (x - mean) * (x - mean);  double s = std::sqrt(ss / (n - 1));  return s / std::sqrt(n);}
    Two steps: the sample SD with n−1 (for {10, 12}, s=2/1≈1.414), then divide by n (here 2), giving 1. Dividing by n in s gives 0.7071 for the second test’s data instead of 0.7559, a small bias that matters for small samples. Dividing s by n instead of n is the other common slip.
  173. 11. Sampling and the central limit theorem · When the normal approximation can be trusted · QuizWhich sample is the CLT least likely to describe well, for the sampling distribution of the mean?C. 15 random households’ incomes, a strongly right-skewed populationSmall n and strong skew is the bad combination: a few very rich households can drag a mean of 15 around, so the sampling distribution is still skewed. Heights are symmetric, so even 12 is fine, and 200 waits is plenty despite the skew.
  174. 11. Sampling and the central limit theorem · Practice problems · ProblemRoll a fair die twice and take the mean of the two rolls. Using the 36 equally likely pairs, what is the probability that the mean is at least 4.5? What is the probability that it is exactly 3.5?P(x‾≥4.5) 5/18 ≈ 0.277778; P(x‾=3.5) 1/6 ≈ 0.166667
    1. The mean is the total divided by 2, so x‾≥4.5 means a total of at least 9. Count the pairs:
    2. total 9:(3,6),(4,5),(5,4),(6,3)4 pairstotal 10:(4,6),(5,5),(6,4)3 pairstotal 11:(5,6),(6,5)2 pairstotal 12:(6,6)1 pair
    3. That is 4+3+2+1=10 pairs of 36, so P(x‾≥4.5)=1036=518≈0.278.
    4. A mean of exactly 3.5 is a total of 7: (1,6), (2,5), (3,4), (4,3), (5,2) and (6,1), 6 pairs. So P(x‾=3.5)=636=16, the tallest bar of the sampling distribution.
  175. 11. Sampling and the central limit theorem · Practice problems · ProblemFive tomato plants measure 4, 7, 7, 9 and 13 cm. Find the sample mean, the sample standard deviation s (dividing by n−1) and the estimated standard error of the mean, s/n.x‾ 8 cm; s sqrt(11) ≈ 3.31662 cm; SE sqrt(11/5) ≈ 1.48324 cm
    1. The mean: x‾=4+7+7+9+135=405=8 cm.
    2. The deviations from 8 are −4,−1,−1,1,5. Square and add them:
    3. ∑(xi−x‾)2=16+1+1+1+25=44s2=445−1=11s=11≈3.32 cm
    4. The estimated standard error:
    5. SE=sn=115=2.2≈1.48 cm
    6. Single plants vary by about 3.3 cm; the mean of five plants would typically miss μ by about 1.5 cm.
  176. 11. Sampling and the central limit theorem · Practice problems · ProblemOne roll of a fair die has mean μ=3.5 and variance σ2=35/12. You roll it 105 times and take the mean. What is the standard error of that mean? Between which two values do about 95% of such means fall, using μ±2SE?SE 1/6 ≈ 0.166667; Lower end 19/6 ≈ 3.16667; Upper end 23/6 ≈ 3.83333
    1. The variance of the mean of 105 rolls is σ2/n:
    2. σ2n=35/12105=3512×105=136,SE=136=16≈0.167
    3. The band is μ±2SE:
    4. 3.5±2×16=3.5±13,from 196≈3.17 to 236≈3.83
    5. A single roll can be anything from 1 to 6, but about 95% of the time the mean of 105 rolls lands within a third of a point of 3.5.
  177. 11. Sampling and the central limit theorem · Practice problems · ProblemA lift’s sign says 12 people or 960 kg. Adult weights have mean 75 kg and standard deviation 12 kg. Twelve adults chosen at random get in. Find the standard error of their mean weight, the z-score of the mean weight that makes the total exactly 960 kg, and the probability that the total is over 960 kg. Treat the mean as normal and use Φ(1.44)=0.9251.SE of the mean sqrt(12) ≈ 3.4641 kg; z 5/sqrt(12) ≈ 1.44338; P(total > 960 kg) 0.0749
    1. A total of 960 kg for 12 people is a mean of 960/12=80 kg, so this is a question about x‾:
    2. SE=1212=12≈3.46 kg
    3. Standardise a mean of 80 kg:
    4. z=80−753.46≈1.44P(total>960)=P(x‾>80)≈1−Φ(1.44)=1−0.9251=0.0749
    5. About 7.5% of random groups of 12 adults would be over the limit, which is why lifts are built with a safety margin. With only 12 people, the normal shape relies on adult weights being roughly bell-shaped to begin with.
  178. 12. Estimating: confidence intervals · A point estimate is one best guess · QuizWhich estimator of the population variance σ2 is unbiased, for a simple random sample of size n?B. The sum of squared deviations from x‾, divided by n−1Values sit a little closer to their own mean x‾ than to the true μ, so squared deviations from x‾ run small. Dividing by n−1 instead of n exactly makes up for it on average. (The square root, s, is still slightly biased for σ, but much less so, and nobody minds.)
  179. 12. Estimating: confidence intervals · An interval is the estimate plus or minus a margin · ProblemA machine fills bags of flour, and from long experience the fill weights have σ=8 g. A random sample of 16 bags has mean x‾=1003 g. Find the standard error, the margin of error and the 95% confidence interval for the mean fill μ, with z∗=1.96.SE 2 g; Margin of error 3.92 g; Lower end 999.08 g; Upper end 1006.92 g
    1. SE=σn=816=2 gmargin=z∗×SE=1.96×2=3.92 ginterval=1003±3.92=(999.08, 1006.92) g
    2. The label’s 1000 g is inside the interval, so it is one of the plausible values for μ: these 16 bags give no clear sign that the machine’s mean is off.
  180. 12. Estimating: confidence intervals · More confidence costs a wider interval · QuizFrom the same sample of plants, a 95% interval is (40.04, 43.96) cm. What would the 99% interval be?C. (39.42, 44.58)Same centre and SE, but z∗=2.576: 42.0±2.576×1=(39.42,44.58). Being surer you’ve caught μ needs a wider net. (40.36, 43.64) is the 90% interval, with 1.645.
  181. 12. Estimating: confidence intervals · Ninety-five per cent is about the method, not this interval · QuizA 95% confidence interval for the mean wait at a coffee shop is (3.35, 5.05) minutes. Which statements are correct?C. If we sampled again and again, about 95% of intervals made this way would contain μ; D. It is a range of plausible values for the mean wait, from a method that catches the true mean 95% of the timeBoth right answers describe the method. The first is the most common mistake: in this (frequentist) view μ is fixed, so it is either in this interval or not; the 95% belongs to the procedure. The Bayesian module later gives intervals that do carry that probability. The second confuses the mean with single customers, whose waits vary far more widely.
  182. 12. Estimating: confidence intervals · When sigma is unknown, use the t distribution · QuizWhy is t∗ bigger than 1.96 for a 95% interval from a small sample?B. Using s instead of σ adds uncertainty, so you go out further to keep 95% coverageWith few values, s can come out well below σ by chance, and then a z-interval would be too narrow and miss more than 5% of the time. The t distribution’s heavier tails build that risk in. With df = 4 the 95% t∗ is 2.776, so the interval is about 40% wider than a z-interval.
  183. 12. Estimating: confidence intervals · The t interval for a mean · Find the bugThis margin of error comes out far too small. Which line is wrong?Line 9: return tStar * s / std::sqrt(n);The standard error is s/n, not s/n. Dividing by n makes the margin n times too small (4 times for 16 values), so the interval would miss far more often than 5% of the time. The n−1 on line 8 is right: it is the sample standard deviation.
  184. 12. Estimating: confidence intervals · The t interval for a mean · Code challengeWrite tInterval(xs, tStar), which returns the confidence interval for the mean as a pair {low, high}: x‾±t∗s/n, with s dividing by n−1. The caller looks up tStar.One solution:
    Solution
    #include <cmath>#include <utility>#include <vector>
    std::pair<double, double> tInterval(const std::vector<double>& xs,                                    double tStar) {  int n = xs.size();  double mean = 0;  for (double x : xs) mean += x;  mean /= n;  double ss = 0;  for (double x : xs) ss += (x - mean) * (x - mean);  double se = std::sqrt(ss / (n - 1)) / std::sqrt(n);  return {mean - tStar * se, mean + tStar * se};}
    For eight values: x‾=5, s=32/7≈2.138, SE ≈0.756, and 5±2.365×0.756. The two-value test shows why tiny samples are nearly useless: with df = 1, t∗=12.706 and the interval runs from below 0 to nearly 24. Using 1.96 there would claim far more precision than two values can give. auto [low, high] = … unpacks the pair into two named values.
  185. 12. Estimating: confidence intervals · The t interval for a mean · ProblemNine phone batteries last a mean of x‾=41.2 hours, with standard deviation s=3.0 hours. How many degrees of freedom does the t interval use? Find the 95% confidence interval for the mean battery life, using t8∗=2.306.Degrees of freedom 8; Lower end 38.894 hours; Upper end 43.506 hours
    1. With n=9 there are n−1=8 degrees of freedom, so t8∗=2.306: bigger than 1.96, because s is only an estimate of σ.
    2. SE=sn=3.09=1.0 hourmargin=2.306×1.0=2.306 hoursinterval=41.2±2.306=(38.894, 43.506) hours
    3. About 38.9 to 43.5 hours. Using 1.96 instead would give a narrower interval, 39.2 to 43.2, which would miss the true mean more than 5% of the time.
  186. 12. Estimating: confidence intervals · An interval for a proportion · Code challengeWrite proportionInterval(successes, n, zStar), returning the pair {low, high} for pˆ±z∗pˆ(1−pˆ)/n.One solution:
    Solution
    #include <cmath>#include <utility>
    std::pair<double, double> proportionInterval(int successes, int n,                                             double zStar) {  double p = double(successes) / n;  double se = std::sqrt(p * (1 - p) / n);  return {p - zStar * se, p + zStar * se};}
    For 50 of 100: pˆ=0.5, SE =0.25/100=0.05, margin =0.098. A frequent slip is forgetting to divide by n inside the square root, or taking the root of the numerator only. In C++ there is one more: successes / n divides two ints, so 50 / 100 is 0, and the interval is [0,0]; double(successes) / n gives 0.5. Note the SE is largest at pˆ=0.5 and shrinks towards 0 and 1.
  187. 12. Estimating: confidence intervals · What makes the margin of error shrink · QuizA survey of 400 people has a margin of error of 4.9 percentage points. What would it be with 1600 people?B. 2.45 pointsFour times the sample is 4=2 times the precision, so the margin halves: 1.960.25/1600=0.0245. Expecting a quarter (1.2 points) is the usual mistake: the margin shrinks with n, not n.
  188. 12. Estimating: confidence intervals · Choosing the sample size before you collect · Code challengeWrite sampleSize(sigma, margin, zStar): the smallest whole n with z∗σ/n≤E, that is (z∗σ/E)2 rounded up.One solution:
    Solution
    #include <cmath>
    int sampleSize(double sigma, double margin, double zStar) {  double root = zStar * sigma / margin;  // that is √n  return std::ceil(root * root);}
    (1.96×12/2)2=138.3, and 138 people would give a margin just over 2, so it must be 139: std::ceil, never std::round. Note how halving the margin quadruples n: precision is bought with the square of effort.
  189. 12. Estimating: confidence intervals · How confidence intervals are misread · QuizTwenty independent research teams each compute a correct 95% confidence interval for the same μ. How many intervals do you expect to miss μ?B. About 1Each misses with probability 0.05, so you expect 20×0.05=1 miss, and no team can tell whether theirs is the one. This is why a single surprising result deserves caution, and it leads straight to the problem of many tests in the next modules.
  190. 12. Estimating: confidence intervals · Practice problems · ProblemIn a random sample of 400 shoppers, 240 say they prefer paying by card. Find the sample proportion, its standard error, and the 95% confidence interval for the proportion of all shoppers who prefer card (z∗=1.96).pˆ 0.6; SE sqrt(0.6*0.4/400) ≈ 0.0244949; Lower end 0.552; Upper end 0.648
    1. pˆ=240/400=0.6. There are 240 successes and 160 failures, both well over 10, so the normal approximation is fine.
    2. SE=0.6×0.4400=0.0006≈0.0245margin=1.96×0.0245≈0.048interval=0.6±0.048=(0.552, 0.648)
    3. Between about 55% and 65% of all shoppers prefer card. A majority looks likely: the whole interval is above 0.5.
  191. 12. Estimating: confidence intervals · Practice problems · ProblemYou want to estimate the mean commuting time in a city to within ±2 minutes. A pilot survey suggests σ≈15 minutes. How many commuters do you need for 95% confidence (z∗=1.96)? And for 99% (z∗=2.576)?For 95% 217 commuters; For 99% 374 commuters
    1. n95=(1.96×152)2=14.72=216.09→217n99=(2.576×152)2=19.322≈373.26→374
    2. Both round up: 216 commuters would give a margin slightly over 2 minutes. Going from 95% to 99% confidence costs about 70% more people, since (2.576/1.96)2≈1.73.
  192. 12. Estimating: confidence intervals · Practice problems · ProblemA pollster wants a margin of error of 2 percentage points (E=0.02) at 95% confidence (z∗=1.96). How many people must she ask if she plans with p=0.5? A past poll suggests p is near 0.2: how many would she need then?Planning with p=0.5 2401 people; Planning with p=0.2 1537 people
    1. With p=0.5, σ=0.25=0.5:
    2. n=(1.96×0.50.02)2=492=2401
    3. With p=0.2, σ=0.2×0.8=0.4:
    4. n=(1.96×0.40.02)2=39.22=1536.64→1537
    5. Planning with 0.5 is the safe choice: if the guess of 0.2 were wrong and p were near 0.5, 1537 people would give a margin of about 2.5 points instead of 2.
  193. 12. Estimating: confidence intervals · More practice problems · ProblemA report gives a 95% confidence interval for a mean of 12.4 to 15.6 kg, made with z∗=1.96. What are the sample mean and the standard error? What is the 90% interval from the same data (z∗=1.645)?x‾ 14 kg; SE 1.6/1.96 ≈ 0.816327 kg; 90% lower end 14 - 1.645*1.6/1.96 ≈ 12.6571 kg; 90% upper end 14 + 1.645*1.6/1.96 ≈ 15.3429 kg
    1. The centre is the estimate, and half the width is the margin:
    2. x‾=12.4+15.62=14,margin=15.6−12.42=1.6
    3. SE=1.61.96≈0.816 kg
    4. Same estimate and standard error, smaller critical value:
    5. 14±1.645×0.816=14±1.343=(12.657, 15.343) kg
    6. The 90% interval is narrower because it claims less: its method misses about 1 time in 10 instead of 1 in 20.
  194. 12. Estimating: confidence intervals · More practice problems · ProblemFifty independent studies each make a correct 90% confidence interval for their own parameter. How many of the intervals do you expect to miss their parameter? What is the probability that all fifty contain it?Expected misses 5; P(all fifty contain it) 0.9^50 ≈ 0.00515378
    1. Each interval misses with probability 1−0.90=0.1, so the number of misses is binomial with n=50 and p=0.1:
    2. E[misses]=np=50×0.1=5
    3. The intervals are independent, so multiply:
    4. P(all fifty hit)=0.950≈0.0052
    5. With fifty 90% intervals it is almost certain that some miss, about 5 of them, and nobody can tell which.
  195. 13. Hypothesis tests and p-values · A test asks whether chance alone could explain the data · Put in orderPut the steps of a hypothesis test in order.1. State the null and alternative hypotheses 2. Choose a significance level, such as 0.05 3. Collect the data 4. Compute a test statistic from the data 5. Find the p-value: how likely a result this extreme is if the null is true 6. Compare the p-value with the significance level and decideThe hypotheses and the significance level come before you look at the data. Choosing them afterwards, once you know what the data say, lets you tilt the test towards the answer you want, which is one of the misuses at the end of this module.
  196. 13. Hypothesis tests and p-values · The null hypothesis is the boring explanation · QuizA website changes its sign-up button. Its old sign-up rate was 10%. You want to know whether the new button changes the rate. Which is the null hypothesis?A. p=0.10The null is "no change": the true rate p is still 0.10. p≠0.10 is the alternative. pˆ is the sample proportion, which you can just look at: hypotheses are about the unknown population value, not about the data.
  197. 13. Hypothesis tests and p-values · A test statistic measures distance in standard errors · Fill the blanksComplete the z statistic for a sample mean xBar against the null value mu0.1: sigma, 2: n, 3: mu0, 4: seThe standard error is σ/n, not σ itself: averages of many values wobble much less than single values. Dividing by σ instead is the usual slip, and it makes every difference look small.
  198. 13. Hypothesis tests and p-values · A test statistic measures distance in standard errors · ProblemA machine should fill bottles with a mean of 500 ml, and its fills have σ=4 ml. A random sample of 25 bottles has mean x‾=498.4 ml. Testing H0:μ=500, find the standard error and the z statistic.SE 0.8 ml; z -2
    1. SE=425=45=0.8 mlz=498.4−5000.8=−1.60.8=−2
    2. The sample mean is 2 standard errors below the claimed 500 ml. The sign says which way; how surprising that is, is the p-value’s job.
  199. 13. Hypothesis tests and p-values · The p-value is how surprising the data would be under the null · QuizThe coffee shop test gives p=0.0082. Which sentence is right?B. If the true mean were 4 minutes, a sample mean of 4.6 or more would happen in about 0.82% of samples.A p-value is computed assuming H0 is true, so it cannot be the probability that H0 is true. It is a statement about the data given the hypothesis, not the hypothesis given the data. Reading it backwards (options one and three) is the most common mistake in all of statistics. Probabilities of hypotheses need Bayesian methods, later in the course.
  200. 13. Hypothesis tests and p-values · The significance level is the line you draw in advance · QuizA test at α=0.05 gives p=0.08. What do you conclude?B. Fail to reject H0: the data are not strong enough evidence against it0.08 is above 0.05, so the evidence does not reach the bar you set. That is all it says: the null survives, it is not proven. A bigger sample might well find the effect.
  201. 13. Hypothesis tests and p-values · One-sided and two-sided tests · Code challengeWrite zTest(xBar, mu0, sigma, n), returning a ZResult with the z statistic and the two-sided p-value. normalCdf(z) is written for you: it gives P(Z≤z).One solution:
    Solution
    #include <cmath>
    double normalCdf(double z) {  return 0.5 * (1 + std::erf(z / std::sqrt(2.0)));}
    struct ZResult {  double z;  double p;};
    ZResult zTest(double xBar, double mu0, double sigma, int n) {  double z = (xBar - mu0) / (sigma / std::sqrt(n));  double p = 2 * (1 - normalCdf(std::abs(z)));  return {z, p};}
    The two-sided p-value is both tails: 2(1−Φ(|z|)). The std::abs matters: without it, a negative z gives 2(1−Φ(−2.4))≈1.98, which is not even a probability. A quick sanity check for any p-value code: it must land between 0 and 1, and equal 1 when the data match the null exactly.
  202. 13. Hypothesis tests and p-values · When sigma is unknown, the t-test takes its place · Code challengeWrite tStatistic(xs, mu0): the one-sample t statistic of the data xs against mu0. Use the sample standard deviation, dividing by n−1.One solution:
    Solution
    #include <cmath>#include <vector>
    double tStatistic(const std::vector<double>& xs, double mu0) {  int n = xs.size();  double mean = 0;  for (double x : xs) mean += x;  mean /= n;  double squares = 0;  for (double x : xs) squares += (x - mean) * (x - mean);  double s = std::sqrt(squares / (n - 1));  return (mean - mu0) / (s / std::sqrt(n));}
    The mean of the eight waits is 4.7 and s≈0.545, so t=0.7/(0.545/8)≈3.63. Dividing the squares by n instead of n−1 makes s a little too small and t a little too big: with 8 values, about 7% too big. With 7 degrees of freedom, t=3.63 gives a two-sided p≈0.008.
  203. 13. Hypothesis tests and p-values · When sigma is unknown, the t-test takes its place · ProblemA battery maker claims a mean life of 1200 hours. You test 36 batteries: x‾=1158 hours and s=90 hours. Find the standard error, the t statistic and its degrees of freedom. (The two-sided critical value at α=0.05 for those degrees of freedom is 2.030.)SE 15 hours; t −2.8; Degrees of freedom 35
    1. SE=9036=15 hourst=1158−120015=−4215=−2.8,36−1=35 degrees of freedom
    2. |t|=2.8 is beyond the critical value 2.030, so at α=0.05 you reject the claim of a 1200-hour mean: the batteries seem to last less. (The two-sided p-value is about 0.008.)
  204. 13. Hypothesis tests and p-values · Two ways to be wrong · QuizA smoke alarm’s null hypothesis is "there is no fire". It stays silent while the kitchen burns. Which error is that?B. Type II errorThe null ("no fire") was false and the alarm failed to reject it: a missed effect, Type II. Going off over burnt toast would be a Type I error, a false alarm. Making an alarm more sensitive cuts Type II errors and adds Type I ones: for a fixed amount of data, lowering one raises the other.
  205. 13. Hypothesis tests and p-values · Power is the chance of finding an effect that is there · QuizWhich of these raise the power of a test? Pick all that do.A. A larger sample; B. A larger true effect; D. Less noisy measurements (smaller σ)More data, a bigger effect and less noise all push the alternative’s curve further from the null’s. A smaller α moves the critical line right, so fewer real effects pass it: fewer false alarms, but less power. Studies are planned to have about 80% power; d=0.5 needs n=25 for that here.
  206. 13. Hypothesis tests and p-values · Tests and confidence intervals tell the same story · QuizA 95% confidence interval for a website’s mean session length is 3.2 to 5.8 minutes. A two-sided test of H0:μ=5 at α=0.05…B. fails to reject H05 is inside the interval, so it is one of the values the data find plausible at the 95% level, and the matching test fails to reject. Being off-centre does not matter: every value inside the interval survives the test.
  207. 13. Hypothesis tests and p-values · Run enough tests and something will be significant · QuizA team tests whether 20 colours of sweets cause headaches. Only green gives p=0.03, and the headline is "Green sweets cause headaches". What is the best response?B. With 20 tests, one significant result is about what chance alone would give: test green again on new dataWith 20 true nulls you expect one p-value below 0.05 on average. The honest moves are to correct for the number of tests (next module) or to treat green as a lead and replicate. Results found by searching are hypotheses, not conclusions.
  208. 13. Hypothesis tests and p-values · Practice problems · ProblemA test of H0:μ=50 gives z=−2.6. Find the p-value against H1:μ<50, and against H1:μ≠50. Use Φ(2.6)=0.9953.One-sided p 0.0047; Two-sided p 0.0094
    1. Against H1:μ<50, only small values count as extreme:
    2. p=P(Z≤−2.6)=1−Φ(2.6)=1−0.9953=0.0047
    3. Against H1:μ≠50, both tails count:
    4. p=P(|Z|≥2.6)=2×0.0047=0.0094
    5. Both are below 0.01. Each is the chance of a result this extreme if μ=50, not the chance that μ=50.
  209. 13. Hypothesis tests and p-values · Practice problems · ProblemFor the coffee shop, x‾=4.6 minutes, σ=1.5 minutes and n=36, and the two-sided test of μ=4 gave p≈0.0164. Find the 99% confidence interval for μ (z∗=2.576). Does a two-sided test at α=0.01 reject μ=4?Lower end 3.956 min; Upper end 5.244 min
    1. 4.6±2.576×0.25=4.6±0.644=(3.956, 5.244)
    2. 4 is inside the 99% interval, so the test at α=0.01 does not reject. That matches the p-value: 0.0164 is below 0.05 but above 0.01. The same data can be significant at one level and not at a stricter one, which is why the level is fixed in advance.
  210. 13. Hypothesis tests and p-values · Practice problems · ProblemA one-sided z-test at α=0.05 rejects when z≥1.645. The true effect is d=0.4 standard deviations and n=36. Where is the statistic centred when the effect is real, and what is the power? What is the power with n=64? Use Φ(0.755)=0.775 and Φ(1.555)=0.940.Centre dn 2.4; Power with n=36 0.775; Power with n=64 0.94
    1. dn=0.4×36=0.4×6=2.4
    2. power=1−Φ(1.645−2.4)=1−Φ(−0.755)=Φ(0.755)≈0.775
    3. With n=64 the centre moves to 0.4×8=3.2:
    4. power=1−Φ(1.645−3.2)=Φ(1.555)≈0.940
    5. With 36 people a real effect of this size is missed about 22% of the time; 64 people bring that down to 6%.
  211. 13. Hypothesis tests and p-values · More practice problems · ProblemA lab runs 8 independent tests at α=0.05, and in fact every null hypothesis is true. What is the probability of at least one significant result? How many false alarms does it expect? What significance level for each test would make the chance of any false alarm exactly 0.05?P(at least one) 1 - 0.95^8 ≈ 0.33658; Expected false alarms 0.4; Level for each test 1 - 0.95^(1/8) ≈ 0.00639115
    1. P(at least one)=1−0.958≈1−0.6634=0.3366
    2. Each test is a false alarm with probability 0.05, so the expected number is 8×0.05=0.4.
    3. For an overall rate of exactly 0.05, each test needs a level a with:
    4. 1−(1−a)8=0.05(1−a)8=0.95a=1−0.951/8≈0.00639
    5. That is very close to 0.05/8=0.00625, the simpler Bonferroni correction of the next module.
  212. 13. Hypothesis tests and p-values · More practice problems · ProblemA screening programme runs 250 tests at α=0.05. In 200 of them the null hypothesis is true; in the other 50 there is a real effect, and each of those tests has power 0.9. How many Type I errors and how many Type II errors do you expect? What share of the significant results are real effects?Type I errors 10; Type II errors 5; Share of significant results that are real 45/55 ≈ 0.818182
    1. Type I errors come from the 200 true nulls: 200×0.05=10 expected.
    2. Type II errors come from the 50 real effects: each is missed with probability 1−0.9=0.1, so 50×0.1=5.
    3. The significant results are the 10 false alarms plus the 50×0.9=45 real effects found:
    4. 4510+45=4555≈0.818
    5. About 18% of the “discoveries” are false alarms, far more than the 5% that α might suggest. The final module returns to this.
  213. 14. Comparing groups: t-tests, chi-squared and ANOVA · A difference in means is only convincing next to the spread · QuizWhich result is the strongest evidence that the fertiliser works?C. A gap of 3 cm, standard deviations of 2 cm, 50 plants per groupEvidence depends on the gap compared with its standard error, and the standard error shrinks with less spread and with more data. The third has both. The gap alone says nothing: a 3 cm gap among plants that vary by 10 cm, with 5 of each, could easily be luck.
  214. 14. Comparing groups: t-tests, chi-squared and ANOVA · The two-sample t-test · Code challengeWrite welchT(a, b): Welch’s t statistic for the mean of a minus the mean of b. Use sample variances (divide by n−1).One solution:
    Solution
    #include <cmath>#include <vector>
    double mean(const std::vector<double>& xs) {  double sum = 0;  for (double x : xs) sum += x;  return sum / xs.size();}
    double variance(const std::vector<double>& xs) {  double m = mean(xs), squares = 0;  for (double x : xs) squares += (x - m) * (x - m);  return squares / (xs.size() - 1);}
    double welchT(const std::vector<double>& a,              const std::vector<double>& b) {  double se = std::sqrt(variance(a) / a.size() +                        variance(b) / b.size());  return (mean(a) - mean(b)) / se;}
    Each group contributes its own s2/n, and the two add under the square root. Adding the standard errors themselves, s1/n1+s2/n2, is the usual slip: it overstates the uncertainty and hides real differences. The sign of t only says which group is bigger.
  215. 14. Comparing groups: t-tests, chi-squared and ANOVA · The two-sample t-test · ProblemTwo classes sat the same test. Class 1: n1=25, x‾1=72, s1=10. Class 2: n2=16, x‾2=66, s2=8. Find the standard error of the difference in means and Welch’s t statistic for class 1 minus class 2.SE sqrt(8) ≈ 2.82843; t 6/sqrt(8) ≈ 2.12132
    1. SE=10225+8216=4+4=8≈2.83t=72−662.83≈2.12
    2. Adding the two standard errors instead, 2+2=4, would give t=1.5 and hide much of the evidence. With Welch’s degrees of freedom (about 37 here) the two-sided p-value is about 0.04.
  216. 14. Comparing groups: t-tests, chi-squared and ANOVA · Paired data: test the differences · QuizTreating the same scores as two independent groups gives t≈0.58 and p≈0.58. Why is the paired test so much stronger?B. It removes the big differences between students, leaving only each student’s changeThe scores range from 55 to 85 because the students differ, and an independent test counts all that as noise (s≈9 to 10). The differences vary far less (sd≈2.5), because each student is compared with themself. Pairing is only right when the data really are paired: using it on unrelated groups is wrong, and so is ignoring a pairing that exists.
  217. 14. Comparing groups: t-tests, chi-squared and ANOVA · Chi-squared compares counts with what you expected · QuizA goodness-of-fit test has k−1 degrees of freedom, for k categories. With χ2=13.4 and a critical value of 11.07 at α=0.05, what do you conclude?A. 5 degrees of freedom; reject: the die looks unfair (p≈0.020)Six faces, but the counts must add up to 60, so once five are known the sixth is fixed: 6−1=5 degrees of freedom. The statistic passes the critical value, so reject. Notice that one face, 6, gives 10 of the 13.4: always look at which cells drive the result.
  218. 14. Comparing groups: t-tests, chi-squared and ANOVA · Chi-squared compares counts with what you expected · ProblemA sweet maker says its four colours are equally common. A bag of 200 has 62 red, 45 green, 38 yellow and 55 blue. Find the expected count of each colour, the chi-squared statistic and its degrees of freedom. (The critical value at α=0.05 is 7.81.)Expected count 50; χ2 6.76; Degrees of freedom 3
    1. Each colour is expected 200/4=50 times.
    2. χ2=12250+(−5)250+(−12)250+5250=144+25+144+2550=6.76
    3. Four colours give 4−1=3 degrees of freedom. 6.76<7.81, so you fail to reject: gaps this size are ordinary chance in a bag of 200 (the p-value is about 0.08).
  219. 14. Comparing groups: t-tests, chi-squared and ANOVA · The chi-squared distribution · Code challengeWrite chiSquared(observed, expected): the sum over the categories of (O−E)2/E.One solution:
    Solution
    #include <vector>
    double chiSquared(const std::vector<double>& observed,                  const std::vector<double>& expected) {  double total = 0;  for (std::size_t i = 0; i < observed.size(); i++) {    double gap = observed[i] - expected[i];    total += gap * gap / expected[i];  }  return total;}
    Squaring makes gaps above and below count alike; dividing by E scales each gap to what is normal for that cell, since a count around 1000 naturally wobbles more than one around 10. Dividing by O instead is a common slip, and it blows up when a cell is observed 0 times.
  220. 14. Comparing groups: t-tests, chi-squared and ANOVA · Chi-squared for independence in a table · Find the bugThis works out the expected counts, but they come out wrong. Which line?Line 15: expected[i][j] = rows[i] * cols[j] / total;Expected counts are row total × column total ÷ grand total. Dividing by the row total just gives the column totals back (100 and 300), which do not even add up to the 200 visitors in the row. A good check: the expected counts in each row and column add up to the same totals as the observed ones.
  221. 14. Comparing groups: t-tests, chi-squared and ANOVA · ANOVA compares the spread between groups with the spread within · QuizWhy use one ANOVA instead of t-tests on every pair of the three groups?A. Three t-tests at 0.05 each give more than a 5% chance of a false alarm in totalThree tests give about 1−0.953≈14% chance of at least one false alarm when all means are equal. ANOVA asks one question at one α. It does not say which group differs: a significant F only says "not all equal", and finding which needs follow-up comparisons with a correction (the last slide before the recap). It assumes roughly normal groups with similar spreads.
  222. 14. Comparing groups: t-tests, chi-squared and ANOVA · Computing the F statistic · Code challengeWrite fStatistic(groups): the one-way ANOVA F statistic for a list of groups, each a std::vector<double>. mean is written for you.One solution:
    Solution
    #include <vector>
    double mean(const std::vector<double>& xs) {  double sum = 0;  for (double x : xs) sum += x;  return sum / xs.size();}
    double fStatistic(const std::vector<std::vector<double>>& groups) {  int k = groups.size();  std::vector<double> all;  for (const std::vector<double>& group : groups)    for (double x : group) all.push_back(x);  int n = all.size();  double grand = mean(all);  double between = 0;  // sum of n_j * (group mean - grand)^2  double within = 0;   // sum of (x - group mean)^2  for (const std::vector<double>& group : groups) {    double m = mean(group);    between += group.size() * (m - grand) * (m - grand);    for (double x : group) within += (x - m) * (x - m);  }  return between / (k - 1) / (within / (n - k));}
    Each sum is divided by its own degrees of freedom: k−1 for between, N−k for within. Forgetting to weight each squared gap by the group’s size nj goes unnoticed when the groups are equal, and gives the wrong answer in the third test, where they are not. With two groups, F is exactly the square of the pooled two-sample t.
  223. 14. Comparing groups: t-tests, chi-squared and ANOVA · Significant is not the same as large · QuizStudy A: 100,000 per group, d=0.02, p<0.001. Study B: 20 per group, d=0.77, p=0.02. Which found the larger effect?B. Study B, because its effect size is much largerThe p-value is smaller in A only because A is enormous. d measures the effect itself, and B’s is almost 40 times bigger. B’s estimate is less precise, though: its confidence interval for d is wide, which is the honest way to say so.
  224. 14. Comparing groups: t-tests, chi-squared and ANOVA · Many comparisons need a stricter bar · QuizYou compare 4 groups pairwise (6 pairs), using Bonferroni at an overall α=0.05. One pair gives p=0.012. Is it significant?B. No: each pair is tested at 0.05/6≈0.0083, and 0.012 is above itSix comparisons share the 0.05, so each gets 0.05/6≈0.0083. Equivalently, multiply the p-value by 6: 0.072>0.05. Bonferroni is simple and always valid, but it is conservative: with many tests it loses a lot of power.
  225. 14. Comparing groups: t-tests, chi-squared and ANOVA · Many comparisons need a stricter bar · Put in orderPut a careful comparison of several fertilisers in order.1. Decide the groups, the outcome and the tests before growing anything 2. Grow the plants and measure them 3. Run one ANOVA on all the groups 4. If it is significant, compare pairs with a correction such as Bonferroni 5. Report effect sizes and confidence intervals for the differencesPlanning first stops you choosing tests to fit the data. ANOVA guards the overall question, corrected pairwise tests answer "which", and effect sizes say whether the differences matter.
  226. 14. Comparing groups: t-tests, chi-squared and ANOVA · Practice problems · ProblemFive runners each ran 400 m before and after a training plan. Times in seconds, before: 62, 58, 65, 60, 70; after: 59, 53, 64, 56, 68. Using the improvements (before minus after), find the mean improvement d‾, its standard deviation sd and the paired t statistic.d‾ 3 s; sd sqrt(2.5) ≈ 1.58114 s; t 3/(sqrt(2.5)/sqrt(5)) ≈ 4.24264
    1. The improvements are 3,5,1,4,2, with mean d‾=15/5=3 s.
    2. ∑(di−d‾)2=0+4+4+1+1=10sd=10/4=2.5≈1.58 st=d‾sd/n=31.58/5≈4.24,4 degrees of freedom
    3. The two-sided critical value for 4 degrees of freedom is 2.776, so the improvement is significant at 0.05 (p≈0.013). Treated as two independent groups, the big differences between runners would swamp it: t would be only about 0.88.
  227. 14. Comparing groups: t-tests, chi-squared and ANOVA · Practice problems · Problem100 patients with back pain were split at random: 50 did a stretching programme and 30 of them improved; 50 had usual care and 20 of them improved. If improving is independent of the group, what is the expected number of improved patients in the stretching group? Find the chi-squared statistic and its degrees of freedom.Expected (stretching, improved) 25; χ2 4; Degrees of freedom 1
    1. The table: stretching, 30 improved and 20 not; usual care, 20 improved and 30 not. In all, 50 improved and 50 did not.
    2. Estretching, improved=50×50100=25
    3. Every expected count is 25, and every observed count is 5 away from it:
    4. χ2=4×5225=4,df=(2−1)(2−1)=1
    5. 4 is above the critical value 3.84, so improving and the programme look related (p≈0.046). Because the groups were randomised, this points to the stretching itself, not to who chose it.
  228. 14. Comparing groups: t-tests, chi-squared and ANOVA · Practice problems · ProblemThree fertilisers were each given to 4 plants. Growth in cm, A: 3, 5, 4, 4; B: 6, 7, 5, 6; C: 8, 7, 9, 8. Find the mean square between groups (MSB), the mean square within groups (MSW) and F.MSB 16; MSW 2/3 ≈ 0.666667; F 24
    1. Group means: x‾A=4, x‾B=6, x‾C=8; grand mean x‾=6.
    2. MSB=4(4−6)2+4(6−6)2+4(8−6)23−1=16+0+162=16
    3. Within each group, the squared deviations from its own mean add to 1+1+0+0=2 (A), 0+1+1+0=2 (B) and 0+1+1+0=2 (C):
    4. MSW=2+2+212−3=69=23,F=162/3=24
    5. An F of 24 is far above 1: the fertilisers clearly differ (p<0.001). ANOVA does not say which pairs differ; that needs corrected follow-up comparisons.
  229. 14. Comparing groups: t-tests, chi-squared and ANOVA · More practice problems · ProblemTwo groups of 10 pupils learned with different methods. Group 1 scored a mean of 52 with s1=6; group 2 scored a mean of 47 with s2=8. Find the pooled standard deviation sp and Cohen’s d.sp sqrt(50) ≈ 7.07107; d 5/sqrt(50) ≈ 0.707107
    1. sp=9×36+9×6418=90018=50≈7.07d=52−477.07≈0.71
    2. A medium-to-large effect by the rough guide (0.5 medium, 0.8 large). With only 10 per group its confidence interval is wide, so the true effect could be much smaller or larger.
  230. 14. Comparing groups: t-tests, chi-squared and ANOVA · More practice problems · ProblemAfter a significant ANOVA on 6 groups, you compare every pair, using Bonferroni at an overall α=0.05. How many comparisons are there, and at what level is each tested? One pair gives p=0.004: what is its Bonferroni-adjusted p-value (the p-value times the number of comparisons)?Comparisons 15; Level for each 0.05/15 ≈ 0.00333333; Adjusted p-value 0.06
    1. (62)=6×52=15 comparisons,0.0515≈0.00333
    2. The pair with p=0.004 is above 0.00333, so it is not significant after the correction. Equivalently, its adjusted p-value is 15×0.004=0.06>0.05.
    3. Uncorrected it would look significant, but with 15 comparisons and no real differences, the chance that at least one p-value falls as low as 0.004 is about 6%.
  231. 15. Linear regression · The best line makes the squared misses smallest · QuizWhy add up the squared residuals instead of the residuals themselves?B. Positive and negative residuals would cancel, so a terrible line could score 0A line far too high on the left and far too low on the right can have residuals that add to exactly 0. Squaring makes every miss count as a positive amount. It also makes big misses count more (a miss of 4 costs 16, a miss of 2 only 4), which is why one wild point can pull a least squares line a long way, as you will see later.
  232. 15. Linear regression · The least squares formulas · Fill the blanksFinish the last two lines: the slope, then the intercept from the means.1: /, 2: meanY, 3: meanXThe slope is Sxy/Sxx. The intercept comes from making the line pass through (x‾,y‾): y‾=b0+b1x‾, so b0=y‾−b1x‾. A common slip is swapping the means, which gives 3−6×62, a nonsense intercept.
  233. 15. Linear regression · The least squares formulas · ProblemA small shop ran online adverts for 1, 2, 3, 4 and 5 hours on five days (x) and sold 3, 7, 5, 11 and 9 items (y). Find the least squares slope b1 and intercept b0.b1 1.6 items per hour; b0 2.2 items
    1. The means are x‾=15/5=3 and y‾=35/5=7. The deviations of x are −2,−1,0,1,2 and of y are −4,0,−2,4,2.
    2. Sxy=(−2)(−4)+(−1)(0)+0+(1)(4)+(2)(2)=16Sxx=4+1+0+1+4=10b1=16/10=1.6b0=7−1.6×3=2.2
    3. The line is yˆ=2.2+1.6x: each extra hour of adverts goes with 1.6 more items sold, on average.
  234. 15. Linear regression · Fitting the line in code · Code challengeWrite fitLine(xs, ys), returning the Line (its intercept and slope) of the least squares line. Use b1=Sxy/Sxx and b0=y‾−b1x‾.One solution:
    Solution
    #include <vector>
    struct Line {  double intercept;  double slope;};
    Line fitLine(const std::vector<double>& xs,             const std::vector<double>& ys) {  int n = xs.size();  double meanX = 0, meanY = 0;  for (int i = 0; i < n; i++) {    meanX += xs[i];    meanY += ys[i];  }  meanX /= n;  meanY /= n;  double sxy = 0, sxx = 0;  for (int i = 0; i < n; i++) {    sxy += (xs[i] - meanX) * (ys[i] - meanY);    sxx += (xs[i] - meanX) * (xs[i] - meanX);  }  double slope = sxy / sxx;  double intercept = meanY - slope * meanX;  return {intercept, slope};}
    Centring on the means first keeps the sums small and accurate. The shortcut formula ∑xiyi−nx‾y‾ gives the same answer on paper but can lose precision on a computer when the numbers are large and close together, because it subtracts two huge, nearly equal values. If every x is the same, Sxx=0 and the slope is undefined: no line can be fitted through a vertical stack of points.
  235. 15. Linear regression · Reading the slope and the intercept · QuizA fit of weekly sales (in units) on advertising spend (in thousands of euros) gives yˆ=120+35x. Which reading is right?A. Each extra thousand euros of advertising goes with about 35 more units sold per week, on averageThe slope is in units of y per unit of x: units sold per thousand euros. It is an average association. Calling it a cause needs an experiment (later in the course), the intercept is a prediction with uncertainty, not a certainty, and a slope in a linear model is an amount, not a percentage.
  236. 15. Linear regression · R squared: the share of the variation the line explains · QuizIn a regression with one predictor, the correlation between x and y is r=−0.6. What is R2?B. 0.36With a single predictor, R2=r2=0.36: the line explains 36% of the variation in y. R2 is never negative for a least squares fit with an intercept, so the sign of the relationship lives in the slope, not in R2. Here 0.973≈0.986 is the correlation of the study data.
  237. 15. Linear regression · R squared: the share of the variation the line explains · ProblemFor the shop data (x = 1, 2, 3, 4, 5 and y = 3, 7, 5, 11, 9), the least squares line is yˆ=2.2+1.6x. Find SSE, SST and R2.SSE 14.4; SST 40; R2 0.64
    1. Residuals, actual minus fitted: 3−3.8=−0.8, 7−5.4=1.6, 5−7=−2, 11−8.6=2.4, 9−10.2=−1.2.
    2. SSE=0.64+2.56+4+5.76+1.44=14.4SST=16+0+4+16+4=40R2=1−14.440=0.64
    3. The line explains 64% of the variation in sales. With one predictor R2=r2, so the correlation is 0.64=0.8, positive like the slope.
  238. 15. Linear regression · Residual plots show what the line missed · QuizThe residual plot for house price against floor area is narrow for small houses and much wider for big ones. What does it tell you?B. The spread of prices grows with size, so predictions for big houses are less preciseA fan shape means the variance is not constant (statisticians say heteroscedastic). The slope may still be fine, but the standard errors that assume equal spread are wrong. Common fixes are modelling the logarithm of price, or using standard errors that allow for unequal spread. Deleting data because it is inconvenient is never the answer.
  239. 15. Linear regression · Outliers and leverage: some points pull harder · QuizAt 10 hours with a score of 60, the new student drags the slope from 6 down to about 0.95. What makes this point so influential?B. It is far from the other points in x, and its y is far from where the line predicted (104)The line predicted 44+6×10=104, so the point misses by 44, and it sits 5 hours beyond the other data, where it has leverage. Place it at 10 hours with a score of 104 and the slope stays 6: high leverage alone does not change the fit if the point agrees with the line. Always plot the data and refit without suspicious points to see how much rides on them.
  240. 15. Linear regression · Predicting inside the data, not beyond it · QuizA line fitted to children aged 2 to 10 says height grows 6 cm a year. What does it predict for age 40, and should you trust it?B. About 3.2 m: do not trust it, growth stops in the late teensThe arithmetic still works (about 1.4 m at age 10, plus thirty years at 6 cm a year, is about 3.2 m), but the line only describes the ages it saw. A model is a summary of the data you have; outside that range it is a guess. This is the most common misuse of regression.
  241. 15. Linear regression · Is the slope real? Inference on the slope · Code challengeWrite slopeTest(xs, ys), returning a SlopeResult: the least squares slope, its standard error se, SE(b1)=s/Sxx with s=SSE/(n−2), and t, b1/SE(b1).One solution:
    Solution
    #include <cmath>#include <vector>
    struct SlopeResult {  double slope, se, t;};
    double mean(const std::vector<double>& v) {  double sum = 0;  for (double x : v) sum += x;  return sum / v.size();}
    SlopeResult slopeTest(const std::vector<double>& xs,                      const std::vector<double>& ys) {  int n = xs.size();  double mx = mean(xs), my = mean(ys), sxy = 0, sxx = 0;  for (int i = 0; i < n; i++) {    sxy += (xs[i] - mx) * (ys[i] - my);    sxx += (xs[i] - mx) * (xs[i] - mx);  }  double slope = sxy / sxx;  double intercept = my - slope * mx, sse = 0;  for (int i = 0; i < n; i++) {    double residual = ys[i] - intercept - slope * xs[i];    sse += residual * residual;  }  double se = std::sqrt(sse / (n - 2)) / std::sqrt(sxx);  return {slope, se, slope / se};}
    The divisor is n−2, not n−1: a line uses two estimated numbers, so only n−2 residuals are free to vary. Dividing by n or n−1 is the usual slip, and it makes the standard error too small and the test too eager to find an effect.
  242. 15. Linear regression · Practice problems · ProblemStill with the shop data: SSE=14.4, Sxx=10, n=5 and b1=1.6. Find s, the standard error of the slope and the t statistic for H0:β1=0. (The two-sided 5% critical value for 3 degrees of freedom is 3.182.)s sqrt(4.8) ≈ 2.19089; SE(b1) sqrt(4.8)/sqrt(10) ≈ 0.69282; t 1.6/sqrt(0.48) ≈ 2.3094
    1. s=14.45−2=4.8≈2.191SE(b1)=2.19110≈0.693t=1.60.693≈2.31,3 degrees of freedom
    2. 2.31<3.182, so the slope is not significant at 0.05, even though R2=0.64. Five points are too few: the 95% interval for the slope, 1.6±3.182×0.693, runs from about −0.60 to 3.80 and includes 0.
  243. 15. Linear regression · Practice problems · ProblemFor a group of students, hours of revision x have mean 10 and standard deviation 5, exam scores y have mean 60 and standard deviation 12, and the correlation is r=0.6. Find the least squares slope and intercept for predicting score from hours, and the predicted score for 15 hours.b1 1.44 points per hour; b0 45.6 points; yˆ at 15 hours 67.2 points
    1. b1=rsysx=0.6×125=1.44b0=y‾−b1x‾=60−1.44×10=45.6yˆ=45.6+1.44×15=67.2
    2. 15 hours is one standard deviation above the mean, and the prediction is only 0.6 of a standard deviation above the mean score: 60+0.6×12=67.2. That shrinking by r is regression to the mean, which module 19 returns to.
  244. 15. Linear regression · Practice problems · ProblemA fit of fuel use (y, litres per 100 km) on car mass (x, in hundreds of kg) gives yˆ=2.5+0.45x, with correlation r=0.9. A car of 1400 kg uses 9.1 litres per 100 km. Find its predicted fuel use, its residual and the R2 of the fit.Predicted 8.8 L/100 km; Residual 0.3 L/100 km; R2 0.81
    1. yˆ=2.5+0.45×14=2.5+6.3=8.8
    2. The residual is 9.1−8.8=0.3 litres per 100 km: this car uses a little more than the line predicts for its mass.
    3. With one predictor, R2=r2=0.92=0.81: mass explains 81% of the variation in fuel use.
    4. Putting in x=1400 instead of 14 is the trap here: always use the units the model was fitted in.
  245. 15. Linear regression · Practice problems · ProblemThe study data of this module are x = 1, 2, 3, 4, 5 hours and y = 51, 54, 62, 70, 73 points, fitted by yˆ=44+6x. A sixth student studied 8 hours and scored 50. What did the line predict for them, what is their residual, and what is the slope refitted to all six? For the six, ∑x=23, ∑y=360, ∑xy=1390 and ∑x2=119.Prediction at 8 hours 92 points; Residual -42 points; New slope 10/(119 - 23^2/6) ≈ 0.324324 points per hour
    1. The old line predicts 44+6×8=92 points, so the residual is 50−92=−42.
    2. Refit with all six. The means are x‾=23/6 and y‾=360/6=60:
    3. Sxy=∑xy−nx‾y‾=1390−6×236×60=1390−1380=10Sxx=∑x2−nx‾2=119−2326≈119−88.17=30.83b1=1030.83≈0.32
    4. One student, far out in x and far below the line, drags the slope from 6 down to about 0.32 points per hour. Before believing either line, look at that point: is it a typing error, or a different kind of student?
  246. 15. Linear regression · Recap · Put in orderPut a regression analysis in a sensible order.1. Draw a scatter plot of the data 2. Fit the least squares line 3. Look at the residual plot for curves, fans and outliers 4. Report the slope with its confidence interval and R2 5. Predict only within the range of the dataPlot first: a scatter plot can show in a second that a line is the wrong model. Fit, then check the residuals before believing any number, because standard errors and p-values rely on the conditions you check there. Only then report, and predict where the data supports it.
  247. 16. Multiple and logistic regression · Each coefficient holds the others fixed · QuizOn its own, the number of bedrooms has a positive slope for price. Add floor area to the model, and the bedrooms coefficient turns negative. How can that be?B. Among houses of the same size, more bedrooms means smaller rooms, which buyers value lessAlone, bedrooms stand in for size: big houses have more bedrooms and cost more. With size in the model, the bedrooms coefficient answers a different question, "same floor area, one more bedroom", and cutting the same space into more rooms can lower the price. A coefficient’s meaning depends on what else is in the model, so always say what was held fixed.
  248. 16. Multiple and logistic regression · Each coefficient holds the others fixed · ProblemUse priceˆ=50+1.8x1−0.9x2, with price in thousands of euros, x1 the floor area in m² and x2 the age in years. Predict the price of an 85 m² house that is 30 years old. Then find the predicted price of house A (100 m², 10 years old) minus that of house B (90 m², 40 years old).85 m², 30 years old 176 thousand €; A minus B 45 thousand €
    1. priceˆ=50+1.8×85−0.9×30=50+153−27=176
    2. For the difference, only the gaps in each predictor matter:
    3. 1.8×(100−90)−0.9×(10−40)=18+27=45
    4. House A is predicted to cost 45 thousand euros more: 18 for being 10 m² bigger, and 27 for being 30 years newer.
  249. 16. Multiple and logistic regression · Categories enter as 0 or 1 · Fill the blanksCode a house in South for a model whose baseline neighbourhood is North.1: 0, 2: 1, 3: 0, 4: 0A South house has isSouth = 1 and isCentre = 0; the baseline, North, is 0 on both. Using three indicators, one per neighbourhood, plus an intercept is the classic mistake (the dummy variable trap): the three always add up to 1, the same as the intercept column, so the coefficients cannot be pinned down.
  250. 16. Multiple and logistic regression · Interactions let one slope depend on another variable · QuizWith g=0 and h=0.3, how much more is a 120 m² house with a garage predicted to cost than one without?C. 36 thousandThe garage’s effect is g+h×size=0+0.3×120=36 thousand euros. With an interaction there is no single "garage effect": it depends on size. Reading g alone as the garage effect is the usual mistake; here it is the effect at size 0, which no house has.
  251. 16. Multiple and logistic regression · Predictors that move together blur each other · QuizA model has both "height in cm" and "height in inches" as predictors. What happens, and what is the fix?B. They are perfectly correlated, so the coefficients cannot be separated; drop one of themInches are centimetres divided by 2.54, so Rj2=1 and the VIF is infinite: any split of the effect between the two fits equally well. Drop one, or combine correlated predictors into one. Note that the predictions are fine; only the individual coefficients are meaningless.
  252. 16. Multiple and logistic regression · More predictors always fit better, and that is the trap · QuizYou add a column of random numbers to a regression. What happens to R2 and to adjusted R2?B. R2 goes up a little (or stays); adjusted R2 usually goes downLeast squares can only reduce SSE with an extra column, so R2 cannot fall. Adjusted R2 divides by n−k−1, so a predictor that adds only chance-sized improvement lowers it. The honest test of a model is how well it predicts data it did not see: cross-validation (a later module) does exactly that.
  253. 16. Multiple and logistic regression · Coefficients act on the log odds · QuizWith b1=0.5, what does one more visit do?B. Multiplies the odds of buying by about 1.65The model is linear in log odds, so the effect is multiplicative on the odds: e0.5≈1.65. The change in probability is not constant: from 2 to 3 visits it goes from 0.119 to 0.182, while from 10 to 11 visits it goes from 0.881 to 0.924. Reading a coefficient as a change in probability is the common mistake.
  254. 16. Multiple and logistic regression · Coefficients act on the log odds · Code challengeWrite sigmoid(z), 1/(1+e−z); probability(b0, b1, x), the logistic model’s p; and oddsRatio(b1), eb1.One solution:
    Solution
    #include <cmath>
    double sigmoid(double z) {  return 1 / (1 + std::exp(-z));}
    double probability(double b0, double b1, double x) {  return sigmoid(b0 + b1 * x);}
    double oddsRatio(double b1) {  return std::exp(b1);}
    The sign in the exponent matters: std::exp(z) instead of std::exp(-z) gives 1−p, a curve that falls as visits rise. Writing probability through sigmoid keeps the model in one place. The odds ratio is eb1, not b1: a coefficient of 0.5 is not "50% more likely".
  255. 16. Multiple and logistic regression · Coefficients act on the log odds · ProblemA logistic model for passing a driving test gives ln⁡p1−p=−4+0.8x, where x is the number of practice drives. What is the probability of passing after 5 drives, and after 7? By what factor does each extra drive multiply the odds?p after 5 drives 0.5; p after 7 drives 1/(1 + exp(-1.6)) ≈ 0.832018; Odds ratio exp(0.8) ≈ 2.22554
    1. After 5 drives the log odds are −4+0.8×5=0, so the odds are e0=1 and p=11+1=0.5.
    2. x=7:ln⁡odds=−4+5.6=1.6odds=e1.6≈4.953p=4.9531+4.953≈0.832
    3. odds ratio=e0.8≈2.23
    4. Two more drives multiply the odds by e0.8×e0.8=e1.6≈4.95, taking them from 1 to about 4.95, while the probability rises from 0.5 to 0.83: odds change by a fixed factor, probabilities by no fixed amount.
  256. 16. Multiple and logistic regression · Gradient descent walks downhill to the best fit · QuizGradient descent’s error grows bigger on every step instead of shrinking. What is the likely cause?A. The learning rate is too large, so each step jumps past the minimum to a higher pointWith too big a step you land on the far side of the valley, higher than where you started, and the next step is bigger still. Too small a rate is the opposite problem: it does converge, just very slowly. A common remedy is to start with a modest rate and halve it whenever the error goes up.
  257. 16. Multiple and logistic regression · Fitting a line by gradient descent · Code challengeWrite descend(xs, ys, rate, steps): start at intercept 0 and slope 0, take steps gradient descent steps on the mean squared error, and return the Line.One solution:
    Solution
    #include <vector>
    struct Line {  double intercept;  double slope;};
    Line descend(const std::vector<double>& xs,             const std::vector<double>& ys, double rate, int steps) {  int n = xs.size();  double intercept = 0;  double slope = 0;  for (int k = 0; k < steps; k++) {    double g0 = 0, g1 = 0;    for (int i = 0; i < n; i++) {      double miss = intercept + slope * xs[i] - ys[i];      g0 += 2.0 / n * miss;      g1 += 2.0 / n * miss * xs[i];    }    intercept -= rate * g0;    slope -= rate * g1;  }  return {intercept, slope};}
    Both gradients are summed with the old coefficients before either changes: updating the intercept first and then using it for the slope’s gradient is a subtle bug: it usually still converges, but it is no longer a true gradient step. Write 2.0 / n, not 2 / n: with an int n of 5, 2 / n is 0, and the line never moves. One step from 0 with rate 0.01: the mean of −2y is −124, so the intercept moves to 1.24; the mean of −2xy is −396, so the slope moves to 3.96. Here descent finds the same 44+6x that the formula gave, which is the point: the method works where no formula exists, as for logistic regression.
  258. 16. Multiple and logistic regression · Practice problems · ProblemA model with k=4 predictors fitted to n=25 observations has R2=0.60. Find its adjusted R2. A fifth predictor lifts R2 to 0.61: what is the new adjusted R2?Adjusted R2, 4 predictors 0.52; Adjusted R2, 5 predictors 1 - 0.39*24/19 ≈ 0.507368
    1. k=4:Radj2=1−0.40×2420=1−0.48=0.52k=5:Radj2=1−0.39×2419≈1−0.493=0.507
    2. R2 went up, as it always does, but adjusted R2 went down: the fifth predictor gained less than a predictor of pure noise would be expected to. Leave it out, or check it with cross-validation.
  259. 16. Multiple and logistic regression · Practice problems · ProblemRegressing floor area on the other predictors of a house-price model gives Rj2=0.75. What is the VIF of floor area, and by what factor is the standard error of its coefficient inflated? What Rj2 would give a VIF of 5?VIF 4; SE inflated by 2; Rj2 for a VIF of 5 0.8
    1. VIF=11−0.75=10.25=4,4=2
    2. The coefficient’s standard error is twice what it would be with uncorrelated predictors. For a VIF of 5:
    3. 11−Rj2=5⇒1−Rj2=0.2⇒Rj2=0.8
  260. 16. Multiple and logistic regression · Practice problems · ProblemA model is priceˆ=40+2size+10garage+0.25(size×garage), with price in thousands of euros, size in m², and garage 1 or 0. How much more is a house with a garage predicted to cost than one without, at 80 m²? At 120 m²? What is the slope of size for houses with a garage?At 80 m² 30 thousand €; At 120 m² 40 thousand €; Slope with a garage 2.25 thousand € per m²
    1. With a garage minus without, at the same size s:
    2. (40+2s+10+0.25s)−(40+2s)=10+0.25s
    3. At 80 m²: 10+0.25×80=30. At 120 m²: 10+0.25×120=40.
    4. For houses with a garage the size terms add up to (2+0.25)s, so the slope is 2.25 thousand euros per m², against 2 without. With an interaction there is no single garage effect: it depends on the size.
  261. 16. Multiple and logistic regression · More practice problems · ProblemFor the shop model ln⁡p1−p=−3+0.5x, with x the number of visits, how many visits give an even chance of buying? How many give a 90% chance?For p=0.5 6 visits; For p=0.9 (ln(9) + 3)/0.5 ≈ 10.3944 visits
    1. An even chance is log odds 0: −3+0.5x=0, so x=6 visits.
    2. A 90% chance is odds of 0.9/0.1=9, so log odds of ln⁡9≈2.197:
    3. −3+0.5x=ln⁡9⇒x=ln⁡9+30.5≈10.39
    4. About 10.4 visits, 4.4 more than for an even chance. The curve is symmetric about its middle, so a 10% chance needs 4.4 fewer than 6, about 1.6 visits.
  262. 16. Multiple and logistic regression · More practice problems · ProblemFit yˆ=b0+b1x to the points (1,2), (2,4) and (3,5) by gradient descent on the mean squared error, starting at b0=b1=0 with learning rate 0.1. The gradients are 2n∑(yˆi−yi) for b0 and 2n∑(yˆi−yi)xi for b1. What are b0 and b1 after one step?b0 11/15 ≈ 0.733333; b1 5/3 ≈ 1.66667
    1. With b0=b1=0 the misses are −2,−4,−5.
    2. g0=23(−2−4−5)=−223≈−7.333g1=23(−2×1−4×2−5×3)=−503≈−16.667
    3. b0=0−0.1×(−7.333)≈0.733b1=0−0.1×(−16.667)≈1.667
    4. Both move from the same old values. The least squares line here is yˆ=0.67+1.5x, so this first step has already taken the slope past it; later steps pull it back.
  263. 16. Multiple and logistic regression · Recap · Put in orderPut one step of gradient descent in order.1. Predict every point with the current coefficients 2. Work out each residual, prediction minus actual 3. Average them into the gradient for each coefficient 4. Move every coefficient against its gradient, times the learning ratePredictions come first because the residuals need them, and the gradient is built from the residuals. All coefficients move together at the end, from the same old values. Then the loop repeats until the coefficients stop changing.
  264. 17. Simulation, the bootstrap and permutation tests · When the maths is hard, simulate · QuizA simulation with 10 000 runs gives an estimate with a standard error of 0.004. How many runs do you need for a standard error of about 0.001?C. 160 000The error goes like 1/N. To make it 4 times smaller you need 42=16 times as many runs: 160 000. Guessing 40 000 is the usual slip: it forgets the square root. This is why simulations are cheap for two decimal places and expensive for five.
  265. 17. Simulation, the bootstrap and permutation tests · When the maths is hard, simulate · ProblemA simulation of 2500 runs gives 900 hits. What is the estimate pˆ, and its standard error? Using pˆ in place of p, how many runs would bring the standard error down to 0.003?pˆ 0.36; SE 0.0096; Runs for an SE of 0.003 25600
    1. pˆ=9002500=0.36,SE=0.36×0.642500=0.4850=0.0096
    2. To go from 0.0096 to 0.003, the SE must shrink by a factor of 0.0096/0.003=3.2, so N must grow by 3.22=10.24:
    3. N=2500×10.24=25600 runs
  266. 17. Simulation, the bootstrap and permutation tests · Computers fake randomness, on purpose · QuizYou run a bootstrap with std::mt19937 gen(7), get an interval, then run it again with a new std::mt19937 gen(7). What happens?A. You get exactly the same intervalThe seed fixes the whole sequence, so every resample, and the interval, repeat exactly. To see how much the answer moves because of the simulation itself, change the seed. Reporting the seed is part of making a simulation reproducible.
  267. 17. Simulation, the bootstrap and permutation tests · Your first Monte Carlo estimate · Code challengeWrite estimateHighRoll(trials, gen): roll two dice trials times using the generator gen and return the fraction of rolls whose sum is at least 10.One solution:
    Solution
    #include <random>
    int die(std::mt19937& gen) {  std::uniform_int_distribution<int> roll(1, 6);  return roll(gen);}
    double estimateHighRoll(int trials, std::mt19937& gen) {  int hits = 0;  for (int i = 0; i < trials; i++) {    if (die(gen) + die(gen) >= 10) hits++;  }  return double(hits) / trials;}
    Count the hits and divide by the number of trials, as a double: hits / trials between two ints is 0. Each die(gen) call draws a fresh number, so the two dice are independent. A common mistake is rolling once and doubling it, 2 * die(gen), which makes the dice always equal (only 5+5 and 6+6 then count, and the estimate heads for 1/3). With 100 000 trials the standard error is about 0.167⋅0.833/100000≈0.0012, so the estimate sits well within 0.005 of the truth, whatever the seed. The generator is passed by reference, std::mt19937&: a copy would carry on from the same state, and two copies replay the same rolls.
  268. 17. Simulation, the bootstrap and permutation tests · The bootstrap: the sample stands in for the population · QuizWhy must a bootstrap resample be drawn with replacement?A. Without replacement, every resample of size n is the original sample reordered, so the statistic never variesTaking all n values without replacement just shuffles them: the mean, median and every other statistic stay the same, so the spread you measure is zero. With replacement, each draw is like a fresh draw from a population shaped like your sample, which is exactly the pretence the bootstrap makes.
  269. 17. Simulation, the bootstrap and permutation tests · Bootstrapping the mean wait at a coffee shop · QuizThe interval, 3.8 to 7.9 minutes, is not centred on 5.7: it reaches 1.9 below but 2.2 above. Why?A. The data are skewed right, and the bootstrap carries that skew into the distribution of the meanA formula like x‾±2SE is symmetric by construction. The percentile interval follows whatever shape the bootstrap distribution has, and with a long right tail in only ten values, high resample means are more likely than very low ones. That asymmetry is honest information a symmetric interval hides.
  270. 17. Simulation, the bootstrap and permutation tests · Bootstrapping the mean wait at a coffee shop · ProblemYou make B=4000 bootstrap means and sort them, m(1)≤m(2)≤⋯≤m(4000). For a 90% percentile interval, cut 5% off each end. Which sorted positions are the lower and upper ends?Lower end m(i): i= 201; Upper end m(j): j= 3800
    1. 5% of 4000 is 200. Cut 200 values off the bottom, m(1) to m(200): the lower end is the next one, m(201).
    2. Cut 200 off the top, m(3801) to m(4000): the upper end is m(3800).
    3. In code, counting from 0, these are sorted[200] and sorted[3799]: the same std::floor(0.05 * B) and std::ceil(0.95 * B) - 1 as in the next challenge, with 0.05 and 0.95 for a 90% interval.
  271. 17. Simulation, the bootstrap and permutation tests · Write the bootstrap · Code challengeWrite bootstrapInterval(data, B, gen): make B resamples of data (with replacement), take each one’s mean, sort the means, and return the pair {sorted[floor(0.025 * B)], sorted[ceil(0.975 * B) - 1]}.One solution:
    Solution
    #include <algorithm>#include <cmath>#include <random>#include <utility>#include <vector>
    std::pair<double, double> bootstrapInterval(    const std::vector<double>& data, int B, std::mt19937& gen) {  int n = data.size();  std::uniform_int_distribution<int> pick(0, n - 1);  std::vector<double> means;  for (int b = 0; b < B; b++) {    double sum = 0;    for (int i = 0; i < n; i++) sum += data[pick(gen)];    means.push_back(sum / n);  }  std::sort(means.begin(), means.end());  int lower = std::floor(0.025 * B);  int upper = std::ceil(0.975 * B) - 1;  return {means[lower], means[upper]};}
    Two loops: B resamples, each of n draws, then std::sort puts the means in order. The classic bug here is the distribution’s range: std::uniform_int_distribution<int> pick(0, n - 1) includes both ends, unlike most ranges in C++, so pick(0, n) would sometimes pick position n, one past the end of the data, which stops the program here and quietly reads garbage elsewhere. The percentile positions come from the prompt: index 50 and 1949 for B=2000 (counting from 0), the m(51) and m(1950) of the last slide. Your generator’s numbers differ from the slide’s, so your interval may differ in the first decimal: that wobble is the simulation’s own error.
  272. 17. Simulation, the bootstrap and permutation tests · Where the bootstrap fails · QuizYou bootstrap the maximum of 20 sensor readings. What does the bootstrap distribution look like?B. About 64% of resamples have exactly the sample maximum, and none is ever above itA resample misses the largest value with chance (1−1/20)20≈0.36, so about 64% of resamples contain it and have exactly that maximum. No resample can go higher. The true maximum of the population is probably above the sample’s, and the bootstrap cannot see it. Extremes need other tools (extreme value theory).
  273. 17. Simulation, the bootstrap and permutation tests · Permutation tests: shuffle the labels · Put in orderPut the steps of a permutation test in order.1. Compute the observed statistic on the real groups 2. Pool all the values together 3. Shuffle the pool and split it into groups of the original sizes 4. Compute the statistic on the shuffled groups 5. Repeat the shuffle many times 6. Report the fraction of shuffles at least as extreme as the observed valueThe observed value comes first, because every shuffle is compared with it. Pooling and shuffling is what “the labels don’t matter” means in code. Keeping the group sizes fixed matters: the null hypothesis is about which values went where, not how many.
  274. 17. Simulation, the bootstrap and permutation tests · Write a permutation test · Find the bugThis shuffle runs, but some orders come up more often than others. Which line is wrong?Line 3: std::uniform_int_distribution<int> pick(0, i);Picking j from the whole vector makes nn−1 equally likely runs, which cannot divide evenly among the n! orders, so some orders are favoured. Picking j from 0 to i gives n⋅(n−1)⋯2=n! runs, one per order. The biased version looks random and quietly skews every p-value built on it.
  275. 17. Simulation, the bootstrap and permutation tests · Write a permutation test · Code challengeWrite permutationPValue(a, b, shuffles, gen): the two-sided p-value for the difference in means, (count + 1) / (shuffles + 1), where count is how many shuffles give an absolute difference at least the observed one. Use the shuffle and mean given.One solution:
    Solution
    #include <cmath>#include <random>#include <utility>#include <vector>
    double mean(const std::vector<double>& xs) {  double sum = 0;  for (double x : xs) sum += x;  return sum / xs.size();}
    void shuffle(std::vector<double>& xs, std::mt19937& gen) {  for (int i = xs.size() - 1; i > 0; i--) {    std::uniform_int_distribution<int> pick(0, i);    std::swap(xs[i], xs[pick(gen)]);  }}
    double permutationPValue(const std::vector<double>& a,                         const std::vector<double>& b, int shuffles,                         std::mt19937& gen) {  double observed = std::abs(mean(a) - mean(b));  std::vector<double> pool = a;  for (double x : b) pool.push_back(x);  int count = 0;  for (int k = 0; k < shuffles; k++) {    shuffle(pool, gen);    std::vector<double> x(pool.begin(), pool.begin() + a.size());    std::vector<double> y(pool.begin() + a.size(), pool.end());    if (std::abs(mean(x) - mean(y)) >= observed - 1e-9) count++;  }  return (count + 1.0) / (shuffles + 1);}
    Compare each shuffled absolute difference with the observed one, then add one to the count and to the total: the real labelling is itself one of the possible arrangements, and this keeps the p-value from ever being 0. Two traps: forgetting std::abs makes it one-sided, and comparing floats exactly can miss ties, because a shuffled mean of 2.5 may come out as 2.4999999999999996. The small tolerance 1e-9 counts them. And one that C++ adds: (count + 1) / (shuffles + 1) divides two ints, which gives 0 for every p-value below 1; count + 1.0 makes it a decimal division.
  276. 17. Simulation, the bootstrap and permutation tests · Cross-validation: test on data the model has not seen · Fill the blanksShuffled data points are dealt into k folds like cards. Complete the line that picks the test points for fold f.1: %, 2: ==, 3: !=pos % k deals positions 0, 1, …, k − 1, 0, 1, … so each fold gets every k-th point and the folds differ in size by at most one. Shuffling first matters: data are often stored in order (by date, by shop), and unshuffled folds would test on a kind of data the model never trained on.
  277. 17. Simulation, the bootstrap and permutation tests · Cross-validation: test on data the model has not seen · QuizYou pick the 10 best of 1000 predictors using all the data, then run 5-fold cross-validation on a model with those 10. The score is excellent. What is wrong?B. The choice of predictors saw the test folds, so the score is optimisticEvery step that learns from data, including choosing predictors, scaling and tuning, must happen inside each training fold. Otherwise information leaks from the test fold into the model. With pure noise and 1000 predictors, this mistake can report impressive accuracy for a model that predicts nothing. Module 20 uses cross-validation to choose between models.
  278. 17. Simulation, the bootstrap and permutation tests · Practice problems · ProblemYou bootstrap a sample of n=10 values. What is the probability that one particular value is left out of a resample? On average, how many of the 10 values appear in a resample at least once?P(left out) 0.9^10 ≈ 0.348678; Expected number that appear 10*(1 - 0.9^10) ≈ 6.51322
    1. P(left out)=(910)10≈0.349
    2. So each value appears with probability 1−0.349=0.651. Adding that up over the 10 values (the expected value of a sum is the sum of the expected values):
    3. 10×(1−0.910)≈6.51
    4. A typical resample holds only about 6 or 7 of the 10 values, some of them more than once. For large n the share tends to 1−1/e≈63%, close to the 64% of the bootstrap maximum quiz.
  279. 17. Simulation, the bootstrap and permutation tests · Practice problems · ProblemGroup A’s values are 7 and 9; group B’s are 2, 4 and 6. Find the observed difference in means, A minus B. How many ways are there to choose which 2 of the 5 values form group A, and what is the exact two-sided permutation p-value, the share of splits with an absolute difference at least as large as the observed one?Observed difference 4; Number of splits 10; Two-sided p 0.2
    1. Observed: 7+92−2+4+63=8−4=4.
    2. There are (52)=10 splits. With S the sum of the pair in group A, the difference is S2−28−S3=5S−566. The most extreme pairs:
    3. {2,4}:S=6⇒−4.33{7,9}:S=16⇒4{2,6}:S=8⇒−2.67{6,9}:S=15⇒3.17
    4. The other six pairs (S = 9, 10, 11, 11, 13, 13) give differences from −1.83 to 1.5. Only {7,9} and {2,4} reach an absolute difference of 4, so p=2/10=0.2.
    5. With so few values no result can be very convincing: even the most extreme split, {2,4}, would give only p=1/10.
  280. 17. Simulation, the bootstrap and permutation tests · Practice problems · ProblemYou run 5-fold cross-validation on 103 data points, dealing the shuffled points into folds with pos % 5. How many points are in fold 0, and how many in fold 4? The five folds’ test errors (mean squared errors) are 4.2, 3.8, 5.0, 4.6 and 4.4: what is the cross-validation score?Fold 0 21 points; Fold 4 20 points; Score 4.4
    1. 103=5×20+3. Positions 100, 101 and 102 have remainders 0, 1 and 2, so folds 0, 1 and 2 get 21 points and folds 3 and 4 get 20.
    2. score=4.2+3.8+5.0+4.6+4.45=225=4.4
    3. Each model was trained on 82 or 83 points and tested on the 20 or 21 it never saw, so 4.4 is an honest estimate of the error on new data.
  281. 17. Simulation, the bootstrap and permutation tests · Practice problems · ProblemA sample of 15 delivery times has standard deviation s=4.2 minutes. What is the formula standard error of the mean, s/n? A large bootstrap treats the sample as the population, dividing by n instead of n−1: about what standard error should it give?Formula SE 4.2/sqrt(15) ≈ 1.08444 min; Bootstrap SE, about 4.2/sqrt(15)*sqrt(14/15) ≈ 1.04766 min
    1. sn=4.215≈1.084 min
    2. Resampling from the 15 values uses their spread with divisor n, which is s14/15, so the bootstrap SE comes out near:
    3. 1.084×1415≈1.048 min
    4. The bootstrap runs about 3% low here. The gap shrinks as n grows, and a real bootstrap adds a little simulation noise on top.
  282. 18. Bayesian statistics · Probability as a degree of belief · QuizIf the prior gives every value of θ the same weight (a flat prior), what shape is the posterior?B. The same shape as the likelihood, rescaled to add up to 1Posterior ∝ likelihood × prior, and a constant prior changes nothing but the scale. So with a flat prior the most plausible value is the one that makes the data most probable: the maximum likelihood estimate of module 20. The posterior is normal only in special or large-sample cases.
  283. 18. Bayesian statistics · Updating with two possible coins · QuizSame data, 4 heads in 5, but now you know that only 1 coin in 10 in the pocket is a trick coin. What is the posterior probability it is the trick coin?B. About 0.23Prior × likelihood: trick 0.1⋅0.4096=0.04096, fair 0.9⋅0.15625=0.140625. The posterior is 0.04096/0.181585≈0.226. The data still favour the trick coin by a factor of 0.4096/0.15625≈2.6 (the Bayes factor), but that is not enough to overturn a prior of 9 to 1 against. Ignoring the prior here is the base-rate fallacy from module 7.
  284. 18. Bayesian statistics · Updating with two possible coins · ProblemA box holds a fair coin and a bent coin that lands heads only 25% of the time. You pick one at random (prior 0.5 each) and flip it 3 times: 3 tails. Find the likelihood of 3 tails for each coin, and the posterior probability that you picked the bent coin.Likelihood, fair coin 1/8 ≈ 0.125; Likelihood, bent coin 27/64 ≈ 0.421875; P(bent | 3 tails) 27/35 ≈ 0.771429
    1. P(3 tails|fair)=0.53=18,P(3 tails|bent)=0.753=2764
    2. With 18=864:
    3. P(bent|data)=0.5×27640.5×864+0.5×2764=278+27=2735≈0.771
    4. The data favour the bent coin by a Bayes factor of 27/8≈3.4, which turns even odds into about 77%.
  285. 18. Bayesian statistics · A grid of possible values · Code challengeWrite gridPosterior(successes, failures, grid): with a flat prior, return the posterior probability of each value in grid, proportional to std::pow(p, successes) * std::pow(1 - p, failures) and adding up to 1.One solution:
    Solution
    #include <cmath>#include <vector>
    std::vector<double> gridPosterior(int successes, int failures,                                  const std::vector<double>& grid) {  std::vector<double> weights;  double total = 0;  for (double p : grid) {    double w = std::pow(p, successes) * std::pow(1 - p, failures);    weights.push_back(w);    total += w;  }  for (std::size_t i = 0; i < weights.size(); i++) weights[i] /= total;  return weights;}
    Multiply prior by likelihood (with a flat prior, just the likelihood), then divide by the sum so the weights add up to 1. That division is the p(data) of Bayes’ theorem. Forgetting it is the usual slip: the shape is right, but the numbers are not probabilities. Grids work for one or two parameters; with ten parameters and 100 points each you would need 10010 grid cells, which is why MCMC exists.
  286. 18. Bayesian statistics · The beta distribution describes a proportion · QuizWhich prior says “the rate is probably near 0.25, and I am fairly sure”?B. Beta(25, 75)Both Beta(1, 3) and Beta(25, 75) have mean a/(a+b)=0.25, but Beta(1, 3) is wide (its standard deviation is about 0.19) while Beta(25, 75) is narrow (about 0.043): it is worth about 100 earlier observations. Beta(75, 25) is centred on 0.75, the mirror image.
  287. 18. Bayesian statistics · Beta prior plus binomial data gives a beta posterior · Fill the blanksComplete the conjugate update.1: k, 2: n - kSuccesses add to a, failures to b. A tempting mistake is adding n to b: that counts the successes twice, once as successes and once as trials.
  288. 18. Bayesian statistics · Beta prior plus binomial data gives a beta posterior · ProblemA designer’s prior for a button’s click rate is Beta(3,7). Then 12 of 20 visitors click. Find the posterior’s a and b, its mean, and the weight the posterior mean puts on the prior mean.a 15; b 15; Posterior mean 0.5; Weight on the prior mean 1/3 ≈ 0.333333
    1. Beta(3+12,7+8)=Beta(15,15),mean=1530=0.5
    2. The weights are a+ba+b+n=1030=13 on the prior mean, 3/10=0.3, and 23 on the data, 12/20=0.6:
    3. 13×0.3+23×0.6=0.1+0.4=0.5
    4. The prior expected about 30%, the data said 60%, and the posterior lands at 50%, two thirds of the way toward the data.
  289. 18. Bayesian statistics · Credible intervals say what people wish confidence intervals said · QuizWhich sentence about the credible interval (0.471,0.836) is correct?B. Given the Beta(2, 2) prior and the data, the cure rate is between 0.471 and 0.836 with probability 0.95A credible interval is a probability statement about the parameter, conditional on the prior and the model. The first option mixes in the frequentist repeated-sampling idea (and about the wrong quantity). The last confuses a parameter, one cure rate for the drug, with a spread across patients.
  290. 18. Bayesian statistics · A normal prior for a mean: precisions add · Code challengeWrite normalUpdate(priorMean, priorSd, sigma, n, xbar), returning the Posterior, its mean and sd, for a normal mean with known sigma.One solution:
    Solution
    #include <cmath>
    struct Posterior {  double mean;  double sd;};
    Posterior normalUpdate(double priorMean, double priorSd, double sigma,                       int n, double xbar) {  double priorPrec = 1 / (priorSd * priorSd);  double dataPrec = n / (sigma * sigma);  double prec = priorPrec + dataPrec;  double mean = (priorPrec * priorMean + dataPrec * xbar) / prec;  return {mean, std::sqrt(1 / prec)};}
    Work in precisions: the data contribute n/σ2 because x‾ has variance σ2/n. The common mistake is averaging the standard deviations or the variances; uncertainty combines by adding precisions, which is why the posterior is narrower than both the prior and the data alone. With a huge prior sd, the answer becomes x‾ with sd σ/n: the frequentist result.
  291. 18. Bayesian statistics · Choosing a prior, and how much it matters · QuizA Beta(20, 20) prior and 20 patients. Roughly how much do the prior and the data each weigh in the posterior mean?B. About two thirds the prior, one third the dataThe weight on the prior is a+ba+b+n=4060=23. A prior worth 40 patients dominates a trial of 20. That is fine if the 40 are real earlier evidence, and a problem if they are only a hunch. Always report the prior, and check how the answer changes with others (a sensitivity analysis).
  292. 18. Bayesian statistics · MCMC: sampling a posterior you cannot write down · Put in orderPut one step of the Metropolis algorithm in order.1. Start from the current value of the parameter 2. Propose a new value nearby, at random 3. Compute the ratio of likelihood × prior at the proposal to that at the current value 4. Accept the proposal with probability min(1, ratio), otherwise stay 5. Record the current value as the next drawUphill moves (ratio above 1) are always taken; downhill moves sometimes. That “sometimes” is what makes the chain visit each region in proportion to its posterior probability, rather than just climbing to the peak. Because only a ratio is used, the unknown normalising constant cancels. When a proposal is rejected, the current value is recorded again: skipping it is a common bug that biases the draws.
  293. 18. Bayesian statistics · Bayesian and frequentist: two questions, often the same answer · QuizA manager asks: “What is the probability that the new page’s sign-up rate is higher than the old one’s?” Which approach answers that question directly?B. A Bayesian posterior for the difference in ratesThe question asks for a probability about parameters, which only a posterior gives: count the fraction of posterior draws where the new rate is higher. A p-value is the probability of data at least this extreme if there were no difference, a different quantity, and confusing the two is one of the most common errors in statistics.
  294. 18. Bayesian statistics · Practice problems · ProblemYour prior for a population mean is μ∼N(100,102). Nine observations with known σ=15 average x‾=110. Find the posterior precision, the posterior mean and the posterior standard deviation.Precision 0.05; Posterior mean 108; Posterior sd sqrt(20) ≈ 4.47214
    1. precision=1100+9225=0.01+0.04=0.05mean=0.01×100+0.04×1100.05=1+4.40.05=108sd=1/0.05=20≈4.47
    2. The data carry four times the prior’s precision, so the mean moves four fifths of the way from 100 to 110. The posterior sd, 4.47, is smaller than both the prior’s 10 and the data’s 15/9=5.
  295. 18. Bayesian statistics · Practice problems · ProblemUse a grid of three values, θ=0.25, 0.5 and 0.75, with a flat prior. You see 2 successes in 3 trials. Find the posterior probability of each grid value.θ=0.25 0.15; θ=0.5 0.4; θ=0.75 0.45
    1. 0.252×0.75=0.0468750.52×0.5=0.1250.752×0.25=0.140625total=0.3125
    2. Divide by the total: 0.046875/0.3125=0.15, 0.125/0.3125=0.4 and 0.140625/0.3125=0.45.
    3. Two successes in three point toward the higher values, but with only three trials 0.5 is nearly as plausible as 0.75.
  296. 18. Bayesian statistics · Practice problems · ProblemA prior for a recovery rate is Beta(4,6). Find its mean and standard deviation. A trial then sees 30 recoveries in 50 patients: what is the posterior mean?Prior mean 0.4; Prior sd sqrt(24/1100) ≈ 0.14771; Posterior mean 34/60 ≈ 0.566667
    1. mean=410=0.4,sd=4×6102×11=241100≈0.148
    2. Beta(34,26),mean=3460≈0.567
    3. The data said 30/50=0.6. The prior, worth 10 observations against the data’s 50, pulls the estimate down only a little.
  297. 18. Bayesian statistics · More practice problems · ProblemBefore a study, you give a hypothesis H probability 0.2. The study’s data are 6 times as probable if H is true as if it is false: a Bayes factor of 6. Find the prior odds of H, the posterior odds, and the posterior probability of H.Prior odds 1/4 ≈ 0.25; Posterior odds 3/2 ≈ 1.5; Posterior probability 0.6
    1. prior odds=0.20.8=14
    2. Dividing Bayes’ theorem for H by Bayes’ theorem for not-H, the evidence p(data) cancels:
    3. P(H|data)P(not H|data)=P(data|H)P(data|not H)×P(H)P(not H)=6×14=32
    4. P(H|data)=3/21+3/2=35=0.6
    5. Evidence of 6 to 1 is solid, yet it only lifts a sceptical 20% to 60%. The same data would take a 50% prior to 6/7≈86%.
  298. 18. Bayesian statistics · More practice problems · ProblemA posterior for a mean μ is normal with mean 108 and standard deviation 20≈4.47. Find the central 95% credible interval, using 1.96, and the posterior probability that μ>100. Use Φ(1.79)=0.9633.Lower end 108 - 1.96*sqrt(20) ≈ 99.2346; Upper end 108 + 1.96*sqrt(20) ≈ 116.765; P(μ>100) 0.9633
    1. 108±1.96×4.47=108±8.77=(99.23, 116.77)
    2. P(μ>100)=P(Z>100−1084.47)=P(Z>−1.79)=Φ(1.79)≈0.963
    3. Both are direct statements about μ, given the prior and the data: a 95% probability that it lies between 99.2 and 116.8, and a 96% probability that it is above 100. A confidence interval cannot be read this way.
  299. 19. Designing studies: experiments, causation and pitfalls · Watching is not the same as intervening · QuizA study follows 10 000 adults for 20 years and finds that those who chose to walk daily had fewer heart attacks. What kind of study is it, and what can it claim?B. An observational study: walking is associated with fewer heart attacksThe people chose whether to walk; nobody assigned it. That makes it observational, however large and long it is. It can show an association, and with care it can be strong evidence, but walkers may differ in other ways (diet, income, health to begin with). Size does not turn observation into an experiment, and observational studies are far from worthless: smoking was shown to cause cancer mostly with them.
  300. 19. Designing studies: experiments, causation and pitfalls · A confounder drives both the cause and the effect · QuizChildren with bigger shoe sizes score higher on reading tests. What is the most likely confounder?B. AgeOlder children have bigger feet and read better. Age causes both, so shoe size and reading move together. Compare children of the same age and the link disappears. When two things are correlated, always ask what could push both of them.
  301. 19. Designing studies: experiments, causation and pitfalls · Randomisation balances what you cannot see · Find the bugThis splits a website’s users into two groups for a test, but the groups are not comparable. Which line is the problem?Line 7: groups[users[i]] = uniform(gen) < 0.5 ? 'A' : 'B';The list is in sign-up order, so the first half, the oldest and most loyal users, all get A. Loyalty then confounds the comparison. The random generator is made but never used. Each user must get a group by chance: uniform(gen) < 0.5. Splitting by position, by id parity, or by day of the week is not randomisation, because each can line up with something that matters.
  302. 19. Designing studies: experiments, causation and pitfalls · Control groups and blinding · Put in orderPut the steps of a randomised controlled trial of a new pain relief tablet in order.1. Write down the outcome, the sample size and the analysis in advance 2. Recruit patients who meet the entry criteria 3. Randomly assign each patient to the tablet or an identical placebo 4. Give the tablets, with neither patients nor assessors knowing which 5. Measure pain scores at the planned time 6. Unblind and compare the groups as plannedPlan first, so the analysis cannot be bent to fit the data (module 20 calls this pre-registration). Patients are recruited before randomisation, so nobody can steer a patient into a group. Blinding lasts until the outcomes are in; only then is the code broken and the planned comparison made.
  303. 19. Designing studies: experiments, causation and pitfalls · An A/B test is an experiment on a website · Code challengeWrite twoProportionZ(xA, nA, xB, nB): the z statistic for B’s rate minus A’s, with the pooled standard error above. The counts are ints.One solution:
    Solution
    #include <cmath>
    double twoProportionZ(int xA, int nA, int xB, int nB) {  double pA = double(xA) / nA;  double pB = double(xB) / nB;  double pooled = double(xA + xB) / (nA + nB);  double se =      std::sqrt(pooled * (1 - pooled) * (1.0 / nA + 1.0 / nB));  return (pB - pA) / se;}
    Under H0 both versions share one rate, so the best estimate of it pools all the sign-ups: (xA+xB)/(nA+nB). Averaging the two rates instead is wrong when the groups differ in size. The usual slip is forgetting that the standard error has a term for each group, 1/nA+1/nB. In C++ every one of these divisions has two ints in it, so each needs a double on one side: xA / nA is 0, and so is 1 / nA, which would make the standard error 0.
  304. 19. Designing studies: experiments, causation and pitfalls · An A/B test is an experiment on a website · ProblemAn A/B test shows each version of a page to 3000 visitors. Version A gets 150 sign-ups and version B gets 195. Find the pooled sign-up rate, the pooled standard error of the difference, and the z statistic for B minus A.Pooled rate pˆ 0.0575; SE sqrt(0.0575*0.9425*2/3000) ≈ 0.00601075; z 0.015/sqrt(0.0575*0.9425*2/3000) ≈ 2.49553
    1. The rates are pˆA=150/3000=0.05 and pˆB=195/3000=0.065. Under H0 they share one rate:
    2. pˆ=3456000=0.0575SE=0.0575×0.9425×(13000+13000)≈0.00601z=0.065−0.050.00601≈2.50
    3. The same 1.5-point gap as the worked example, with fewer visitors per version: z falls from 2.88 to 2.50, but it is still beyond 1.96 (two-sided p≈0.013).
  305. 19. Designing studies: experiments, causation and pitfalls · Selection and survivorship bias · Quiz"Old buildings were built better: the ones from 1800 are still standing, but modern ones crack." What is wrong with this argument?B. It only sees the 1800 buildings that survived; the badly built ones fell down or were demolishedThis is survivorship bias. Most buildings of 1800 are gone, and the poorly built ones went first, so the ones you can still visit are the best of their time. Modern buildings have not been through that filter yet. Whenever a sample has been through a filter, ask what the filter removed.
  306. 19. Designing studies: experiments, causation and pitfalls · Extreme results drift back toward the average · QuizA flight instructor notices that pilots who are praised after a great landing usually do worse next time, and those shouted at after a bad one usually do better. What does this show?B. Probably nothing about praise: extreme landings are followed by more typical ones either wayThis is Daniel Kahneman’s famous example. A great landing had good luck in it, so the next one is likely to be more ordinary, whatever the instructor says; the same in reverse for a bad one. Regression to the mean alone produces exactly this pattern. The fix is a control group: compare praised pilots with similar pilots who got no feedback.
  307. 19. Designing studies: experiments, causation and pitfalls · Extreme results drift back toward the average · Code challengeWrite predictRetest(score, mean, r): the expected second score of someone who got score, when both tests have the same mean and spread and correlate with r.One solution:
    Solution
    double predictRetest(double score, double mean, double r) {  return mean + r * (score - mean);}
    The distance from the mean, x−x‾, shrinks by the factor r. With r=0.6, a score 20 above the mean is expected to come back only 12 above it: 82. With r=0 (pure luck), everyone is expected back at the mean. A common mistake is to think regression means scores become more alike over time; the spread stays the same, because new extreme scorers appear as old ones return.
  308. 19. Designing studies: experiments, causation and pitfalls · Extreme results drift back toward the average · ProblemTwo versions of a reasoning test both have mean 100 and standard deviation 15, and scores on them correlate with r=0.7. A pupil scores 130 on the first. What is their predicted score on the second? And for a pupil who scored 85?After 130 121; After 85 89.5
    1. 130:yˆ=100+0.7×(130−100)=100+21=12185:yˆ=100+0.7×(85−100)=100−10.5=89.5
    2. Both are pulled toward 100: the high scorer is predicted 9 points lower, the low scorer 4.5 points higher, with no change in either pupil. In z-scores, +2 becomes +1.4 and −1 becomes −0.7.
  309. 19. Designing studies: experiments, causation and pitfalls · Simpson’s paradox: the whole can reverse the parts · QuizA new patient arrives and you know the size of their stone. Which table should guide the choice?B. The row for their stone size: compare like with likeWithin each size the patients are comparable, and A wins in both. The overall row mixes a different blend of easy and hard cases into each treatment, so it compares A’s hard cases with B’s easy ones. But do not make "always split the data" a rule: whether to split depends on the causal story. Splitting by a confounder is right; splitting by something the treatment itself causes can create a false difference.
  310. 19. Designing studies: experiments, causation and pitfalls · Causal diagrams say what to adjust for · QuizAmong famous actors, the more talented ones tend to be less good-looking. Suppose fame needs talent or looks, and in the whole population the two are unrelated. What explains the pattern?B. Fame is a collider: among the famous, lacking one trait means you must have had the otherTalent → fame ← looks. Looking only at the famous is adjusting for the collider. An actor who is not very good-looking must be talented to have made it, so within the famous group the two traits look negatively related, though they are not in general. This is collider bias (or Berkson’s paradox), and it is why "control for everything" is bad advice.
  311. 19. Designing studies: experiments, causation and pitfalls · Practice problems · ProblemTwo hospitals treat mild and severe cases. Hospital A: 95 of 100 mild patients survive, and 300 of 400 severe ones. Hospital B: 360 of 400 mild patients survive, and 70 of 100 severe ones. Find each hospital’s overall survival rate, as a percentage.Hospital A 79 %; Hospital B 86 %
    1. A: 95+300100+400=395500=79%,B: 360+70400+100=430500=86%
    2. Overall, B looks better. But within each kind of case A does better: 95% against 90% for mild cases, and 75% against 70% for severe ones.
    3. A treats mostly severe cases (400 of its 500), and severe cases die more often anywhere. Severity is a confounder, and lumping the cases together reverses the comparison: Simpson’s paradox. To choose a hospital for a patient, compare like with like.
  312. 19. Designing studies: experiments, causation and pitfalls · Practice problems · ProblemAn A/B test meant to split 20 000 visitors 50/50 sends 10 300 to A and 9700 to B. If each visitor really had a 0.5 chance of A, what are the expected count in A and the standard deviation of that count? What z does 10 300 give?Expected count 10000; SD of the count sqrt(5000) ≈ 70.7107; z 300/sqrt(5000) ≈ 4.24264
    1. E=np=20000×0.5=10000SD=20000×0.5×0.5=5000≈70.7z=10300−1000070.7≈4.24
    2. A 52/48 split sounds harmless, but with 20 000 visitors it is over 4 standard deviations from 50/50: chance almost never does that. The assignment is broken (a sample ratio mismatch), so the test’s results cannot be trusted until the cause is found.
  313. 19. Designing studies: experiments, causation and pitfalls · Practice problems · ProblemA trial has 80 smokers among its patients, and each patient is assigned to treatment or control by a fair coin. What is the expected number of smokers in the treatment group, and the standard deviation of that number? How many standard deviations above the expected number would 49 smokers be?Expected 40; SD sqrt(20) ≈ 4.47214; z for 49 9/sqrt(20) ≈ 2.01246
    1. E=80×0.5=40,SD=80×0.5×0.5=20≈4.47
    2. z=49−404.47≈2.01
    3. Randomisation balances smoking on average, and a split as uneven as 49 to 31 happens in only about 3% of trials. When a strong predictor like smoking is known in advance, blocking on it (randomising separately among smokers and non-smokers) balances it exactly.
  314. 19. Designing studies: experiments, causation and pitfalls · Practice problems · ProblemIn a randomised trial, 60 of 100 patients on a new tablet improved, against 45 of 100 on placebo. Find the difference in improvement rates, its standard error pˆ1(1−pˆ1)/n1+pˆ2(1−pˆ2)/n2, and the upper end of the 95% interval for the difference (z∗=1.96).Difference 0.15; SE sqrt(0.6*0.4/100 + 0.45*0.55/100) ≈ 0.0698212; Upper end 0.15 + 1.96*sqrt(0.004875) ≈ 0.28685
    1. pˆ1−pˆ2=0.60−0.45=0.15SE=0.6×0.4100+0.45×0.55100=0.004875≈0.06980.15±1.96×0.0698=0.15±0.137=(0.013, 0.287)
    2. The tablet raises the improvement rate by somewhere between about 1 and 29 percentage points. The interval excludes 0, so the effect is significant at 5%, but its size is very uncertain: report the interval, not just “it works”.
    3. A test of no difference uses the pooled SE of the A/B slide, because under H0 the rates are equal; an interval lets each group keep its own rate.
  315. 20. Modelling like an expert · Likelihood turns probability around · QuizWith 7 heads in 10 flips, L(0.7)≈0.267 and L(0.5)≈0.117. What does this say?B. The observed data are about 2.3 times as probable if p = 0.7 as if p = 0.5Likelihoods compare values of the parameter on the same data: 0.267/0.117≈2.3. They do not add up to 1 over p, so they are not probabilities of p. A ratio of 2.3 is weak evidence; a fair coin gives 7 or more heads in 10 about 17% of the time.
  316. 20. Modelling like an expert · Maximum likelihood picks the best-explaining value · Code challengeWrite logLik(waits, rate), the exponential log-likelihood above, and bestRate(waits), which tries every rate from 0.001 to 10 in steps of 0.001 and returns the one with the largest logLik.One solution:
    Solution
    #include <cmath>#include <vector>
    double logLik(const std::vector<double>& waits, double rate) {  double total = 0;  for (double x : waits) total += x;  return waits.size() * std::log(rate) - rate * total;}
    double bestRate(const std::vector<double>& waits) {  double best = 0.001;  for (int i = 1; i <= 10000; i++) {    double rate = i / 1000.0;    if (logLik(waits, rate) > logLik(waits, best)) best = rate;  }  return best;}
    The sum of logs is nln⁡λ, and the exponents add to −λ∑xi. The search agrees with calculus: 1/x‾=1/3. Building the grid as i / 1000.0 avoids the drift you get from adding 0.001 ten thousand times; i / 1000, between two ints, would make every rate a whole number, and 0 for the first 999. Real software climbs the log-likelihood with Newton’s method or gradient ascent instead of a grid, but the idea is the same.
  317. 20. Modelling like an expert · Maximum likelihood picks the best-explaining value · ProblemFive coffee-shop waits are 1.5, 4, 2.5, 3 and 1 minutes. Modelling them as exponential with rate λ, find the maximum likelihood estimate λˆ and the log-likelihood there, ℓ(λˆ)=nln⁡λˆ−λˆ∑xi.λˆ 5/12 ≈ 0.416667 per minute; ℓ(λˆ) 5*ln(5/12) - 5 ≈ −9.37734
    1. The waits add to 1.5+4+2.5+3+1=12, so x‾=12/5=2.4 minutes and λˆ=1/2.4=5/12≈0.417 per minute.
    2. Check with calculus: setting the derivative nλ−∑xi=5λ−12 to zero gives λ=5/12.
    3. ℓ(λˆ)=5ln⁡512−512×12=5ln⁡512−5≈−4.377−5=−9.377
    4. Every other rate gives a lower log-likelihood. The fitted model’s mean wait, 1/λˆ=2.4 minutes, is the sample mean.
  318. 20. Modelling like an expert · Every model trades bias against variance · QuizA model fits its training data almost perfectly (R2=0.99) but predicts new data badly. What is the most likely problem?B. High variance: it has fitted the noise in the training dataA near-perfect training fit with poor new predictions is overfitting: the model has memorised the sample’s noise, which will not repeat. A model with high bias does badly on both training and new data. The fixes are a simpler model, regularisation, or more data, and judging the model on data it did not see.
  319. 20. Modelling like an expert · Compare models on what they have not seen · QuizWhich model does AIC prefer, and why not the degree-8 one?B. The quadratic: its fit is much better than the line’s, and the extra 6 parameters of degree 8 buy only 3.1 of log-likelihoodGoing from the line to the quadratic gains 8.3 in log-likelihood for one parameter: worth it. Going on to degree 8 gains 3.1 for six more parameters, each costing 1 in log-likelihood terms (2 in AIC). Differences in AIC above about 4 are usually taken as clear; 5.8 here. AIC only compares models fitted to the same data; its absolute value means nothing.
  320. 20. Modelling like an expert · Compare models on what they have not seen · Fill the blanksComplete the function that computes AIC from a model’s maximised log-likelihood.1: k, 2: logLikTwice the parameter count is the penalty; minus twice the log-likelihood is the misfit. A common slip is to use the likelihood itself instead of its logarithm, or to forget the minus sign and end up preferring the worst fit.
  321. 20. Modelling like an expert · Compare models on what they have not seen · ProblemModel A has k=3 parameters and maximised log-likelihood −84.2; model B has k=5 and −81.9. Both are fitted to the same n=50 observations. Find each model’s AIC. Then find BIC(B) minus BIC(A), with BIC=kln⁡n−2ln⁡Lˆ.AIC of A 174.4; AIC of B 173.8; BIC(B) − BIC(A) 2*ln(50) - 4.6 ≈ 3.22405
    1. AICA=2×3+168.4=174.4AICB=2×5+163.8=173.8
    2. AIC prefers B, but only by 0.6: as predictors, the two are about equally good.
    3. BICB−BICA=(5−3)ln⁡50+(163.8−168.4)≈7.82−4.6=3.22
    4. BIC charges ln⁡50≈3.9 per parameter instead of 2, so it prefers the smaller model A. When the two criteria disagree, the evidence for the extra parameters is modest.
  322. 20. Modelling like an expert · Regularisation shrinks coefficients toward zero · Code challengeFor a line through the origin, the ridge slope is the sum of x * y divided by (the sum of x * x plus lambda). Write ridgeSlope(xs, ys, lambda).One solution:
    Solution
    #include <vector>
    double ridgeSlope(const std::vector<double>& xs,                  const std::vector<double>& ys, double lambda) {  double sxy = 0, sxx = 0;  for (std::size_t i = 0; i < xs.size(); i++) {    sxy += xs[i] * ys[i];    sxx += xs[i] * xs[i];  }  return sxy / (sxx + lambda);}
    Least squares through the origin gives ∑xy/∑x2=60.7/30≈2.023. The penalty only enlarges the denominator, so the slope shrinks smoothly toward 0 as λ grows, but never reaches it: that is ridge’s signature, where lasso would hit 0 exactly. In practice, standardise the predictors first, so the penalty treats them alike, and do not penalise the intercept.
  323. 20. Modelling like an expert · The reproducibility crisis · QuizA field tests ideas of which 10% are true, with power 0.8 and α=0.05. Of its significant results, what share are real effects?C. About 64%Per 1000 ideas: 100 true, of which 80 come out significant; 900 false, of which 45 come out significant by chance. Real ones: 80/(80+45)=0.64. The "95%" comes from confusing α with the chance a finding is true, the same mistake as reading a p-value as the probability that H0 is true. With power 0.2, the share falls to about 31%.
  324. 20. Modelling like an expert · Pre-register, then report the uncertainty · QuizA researcher tries three outcome measures, with and without outliers, and with two sets of control variables, then reports the one analysis with p = 0.03. Why is that p-value misleading?B. Because it was one of 12 analyses: the chance that at least one reaches p < 0.05 with no real effect is far above 5%3×2×2=12 paths. They are correlated, so the chance is less than 1−0.9512≈0.46, but still well above 0.05. Each analysis may be correct on its own; choosing among them after seeing the results is what breaks the p-value, because it was computed as if there had been only one. This is p-hacking, and it is often done in good faith.
  325. 20. Modelling like an expert · Mastery questions · QuizA 95% confidence interval for the difference in mean scores between two teaching methods is 1.1 to 4.1 points. Which statements are right?A. A two-sided test of "no difference" at α=0.05 would reject it; C. The method that made this interval captures the true difference in 95% of samplesAn interval that excludes 0 corresponds to rejecting H0 at the matching level, and the 95% describes the method across repeated samples. The probability statement about this one interval needs a Bayesian posterior (module 18), which with a flat prior often gives a similar range. Whether 1 to 4 points matters is a question about the subject, not about statistics.
  326. 20. Modelling like an expert · Mastery questions · QuizA company finds that customers who used its new budgeting feature saved 30% more. It plans to tell all customers the feature makes them save more. What is the biggest problem?B. Customers chose to use it: careful savers are more likely to try a budgeting toolSelf-selection: the users differ from the non-users before they ever open the feature, so the comparison is confounded by how keen they were on saving. Even a tiny p-value would not fix it. The clean answer is an A/B test: offer the feature to a random half and compare everyone offered it with everyone not offered it (module 19).
  327. 20. Modelling like an expert · Mastery questions · QuizAn experiment with 2 million users per group finds a difference in sign-up rate of 0.01 percentage points, with p = 0.001. What follows?B. The effect is very probably real but tiny; whether it is worth anything is a business questionThe standard error shrinks like 1/n, so with millions of users even a minute difference is "significant". Significance says the effect is probably not zero, not that it is big. Report the size and its interval and judge it against the cost of the change.
  328. 20. Modelling like an expert · Mastery questions · QuizWhat does the bootstrap assume?B. That the sample is a fair stand-in for the population, drawn independentlyResampling from the sample treats it as a small copy of the population, so it needs a sample that represents it (random, independent draws). It does not need normality, which is its strength. It is not assumption-free: a biased sample gives a confident interval around the wrong value, and very small samples give intervals that are too narrow.
  329. 20. Modelling like an expert · Final challenge: an interval for a difference · Code challengeWrite diffInterval(a, b, c), returning the pair {low, high} for the mean of b minus the mean of a, using the standard error above and critical value c.One solution:
    Solution
    #include <cmath>#include <utility>#include <vector>
    double mean(const std::vector<double>& x) {  double sum = 0;  for (double v : x) sum += v;  return sum / x.size();}
    double variance(const std::vector<double>& x) {  double m = mean(x), squares = 0;  for (double v : x) squares += (v - m) * (v - m);  return squares / (x.size() - 1);}
    std::pair<double, double> diffInterval(const std::vector<double>& a,                                       const std::vector<double>& b,                                       double c) {  double diff = mean(b) - mean(a);  double se = std::sqrt(variance(a) / a.size() +                        variance(b) / b.size());  return {diff - c * se, diff + c * se};}
    The means are 13.375 and 16, so the difference is 2.625. The sample variances are about 2.839 and 1.714, giving SE=2.839/8+1.714/8≈0.754. The usual mistakes: dividing by n instead of n−1, adding the standard errors instead of the variances, or subtracting in the wrong order. With 8 per group, Welch’s t critical value is about 2.16, not 1.96, so the honest 95% interval is a little wider than the first two tests give.
  330. 20. Modelling like an expert · Practice problems: the whole course · ProblemIn a field, 20% of the hypotheses tested are true. Studies have power 0.5 and use α=0.05. What share of significant results are real effects? What would it be if the power rose to 0.9?With power 0.5 5/7 ≈ 0.714286; With power 0.9 9/11 ≈ 0.818182
    1. Per 1000 hypotheses: 200 are true and 200×0.5=100 of them come out significant; 800 are false and 800×0.05=40 of them come out significant by chance.
    2. PPV=100100+40=57≈0.714
    3. With power 0.9, 200×0.9=180 true effects are found:
    4. PPV=180180+40=911≈0.818
    5. Better power helps, but the 40 false alarms from the 800 false hypotheses stay whatever the power. Only testing fewer long shots, or a stricter α, cuts those.
  331. 20. Modelling like an expert · Practice problems: the whole course · ProblemTwo teaching methods were each used with 50 pupils. Method B’s mean score was 72.4 with s=9; method A’s was 68.1 with s=8. Find the standard error of the difference (B minus A) and the 95% interval for it, with z∗=1.96. Does a two-sided test at 0.05 reject “no difference”?SE sqrt(2.9) ≈ 1.70294; Lower end 4.3 - 1.96*sqrt(2.9) ≈ 0.96224; Upper end 4.3 + 1.96*sqrt(2.9) ≈ 7.63776
    1. SE=8150+6450=2.9≈1.703x‾B−x‾A=72.4−68.1=4.34.3±1.96×1.703=4.3±3.34=(0.96, 7.64)
    2. The interval leaves out 0, so the test rejects “no difference” at 0.05 (z=4.3/1.703≈2.53). But the effect could be anywhere from about 1 to 7.6 points: report the interval, not just “significant”.
  332. 20. Modelling like an expert · Practice problems: the whole course · ProblemOf 40 patients in a trial, 28 recovered. Find the 95% Wald confidence interval for the recovery rate (z∗=1.96), and the posterior mean with a flat Beta(1,1) prior.Lower end 0.7 - 1.96*sqrt(0.21/40) ≈ 0.557985; Upper end 0.7 + 1.96*sqrt(0.21/40) ≈ 0.842015; Posterior mean 29/42 ≈ 0.690476
    1. pˆ=0.7,SE=0.7×0.340≈0.07250.7±1.96×0.0725=0.7±0.142=(0.558, 0.842)
    2. Beta(1+28,1+12)=Beta(29,13),mean=2942≈0.690
    3. The two approaches nearly agree on the numbers, but not on the meaning: the interval’s 95% is the method’s hit rate over repeated samples, while the posterior gives probabilities for the recovery rate itself.
  333. 20. Modelling like an expert · More practice: the whole course · ProblemA regression on n=27 points gives slope b1=2.5 with standard error 0.8. Find the t statistic for H0:β1=0 and the lower end of the 95% interval for the slope, using t25∗=2.060. About what standard error would you expect with four times as many points, spread the same way?t 3.125; Lower end 0.852; SE with 4 times the points 0.4
    1. t=2.50.8=3.125,27−2=25 degrees of freedom2.5±2.060×0.8=2.5±1.648=(0.852, 4.148)
    2. Four times the points makes Sxx about four times bigger while s stays about the same, so SE(b1)=s/Sxx halves: about 0.8/2=0.4.
  334. 20. Modelling like an expert · More practice: the whole course · ProblemA lab tests 40 hypotheses at α=0.05. Unknown to it, 10 are real effects, each found with power 0.8, and 30 are true nulls. How many false positives and how many true positives does it expect? What share of its significant results are real?False positives 1.5; True positives 8; Share that are real 8/9.5 ≈ 0.842105
    1. False positives: 30×0.05=1.5. True positives: 10×0.8=8.
    2. 88+1.5=89.5≈0.842
    3. About 84% of its discoveries are real. With Bonferroni at 0.05/40 (module 14) the expected false positives fall to 30×0.00125=0.0375, but the power falls too: every correction trades false alarms for missed effects.
  335. 20. Modelling like an expert · More practice: the whole course · ProblemA coin lands heads 8 times in 10 flips. Find the maximum likelihood estimate of p, the likelihood ratio L(pˆ)/L(0.5), and the one-sided p-value P(X≥8) for a fair coin.pˆ 0.8; L(pˆ)/L(0.5) 0.8^8*0.2^2/0.5^10 ≈ 6.87195; P(X≥8) 56/1024 ≈ 0.0546875
    1. The MLE of a proportion is k/n=8/10=0.8.
    2. L(0.8)L(0.5)=0.88×0.220.510≈0.0067110.000977≈6.87
    3. P(X≥8)=(108)+(109)+(1010)210=45+10+11024=561024≈0.055
    4. The data are about 7 times as probable with p=0.8 as with 0.5, yet the one-sided p-value is just above 0.05. They answer different questions: the likelihood ratio compares two values of p, while the p-value asks how unusual 8 or more heads would be from a fair coin.