Probability: Bayesian and Frequentist Reasoning
Reasoning under uncertainty is fundamental to artificial intelligence, machine learning, and data analysis. Whether evaluating diagnostic tests, assessing classification models, or determining whether an experimental treatment works, engineers must make sound statistical judgments.
In data science, two primary philosophies govern statistical inference:
- Bayesian Inference: Models belief as a probability distribution over hypotheses. When new evidence arrives, Bayes’ Theorem updates this distribution to produce a posterior probability.
- Frequentist Inference: Interprets probability as the long-run frequency of events in repeated experiments. It relies on null hypothesis significance testing, p-values, and confidence intervals without assigning prior probabilities to hypotheses.
These two schools often seem at odds in textbook presentations. In this chapter, we implement both frameworks in pure Gerbil Scheme and examine a classic medical screening problem from both perspectives side by side. We will observe how both methodologies arrive at the exact same practical conclusion: why a screening test with 99% accuracy can yield only a 2% chance of disease, and why extreme statistical significance does not equate to high predictive value.
Theoretical Foundations
Before writing Scheme code, we establish the mathematical concepts used across both schools.
Bayes’ Theorem and Posterior Updating
Let
be a hypothesis (for example, “the patient has the disease”) and
be an observed piece of evidence (such as “the test result is positive”). Bayes’ Theorem computes the conditional probability
:

In this expression:
is the prior probability: the initial belief before seeing new evidence.
is the likelihood: the probability that evidence
occurs given hypothesis
.
is the marginal likelihood (or evidence): the total probability of seeing
across all possible mutually exclusive hypotheses
.
is the posterior probability: the updated belief in
after incorporating
.
The Maximum a Posteriori (MAP) decision rule selects the hypothesis with the highest posterior probability:

The Base Rate Fallacy in Medical Testing
Consider a rare disease that affects 0.1% of the population (
). Suppose a medical laboratory develops an automated test with:
- Sensitivity (True Positive Rate):
- False Positive Rate:
When a patient tests positive, intuition suggests the probability of disease must be near 99%. However, applying Bayes’ Theorem reveals:

Because 99.9% of the population is healthy, the 5% false positive rate applied to that large healthy majority produces roughly 50 false positives for every 1 true positive. Ignoring the base rate (
) is known as the base rate fallacy.
Frequentist Hypothesis Testing and Confidence Intervals
In the frequentist paradigm, we do not assign a prior probability to the patient’s health status. Instead, we formulate a null hypothesis
(for instance, “the test result is independent of disease status”) and collect sample counts:
- True Positives (TP): sick individuals who test positive.
- False Positives (FP): healthy individuals who test positive.
- True Negatives (TN): healthy individuals who test negative.
- False Negatives (FN): sick individuals who test negative.
Pearson’s Chi-Squared Test of Independence
To test whether the test result and actual disease status are statistically associated, we construct a 2×2 contingency table and compute the chi-squared statistic:

where
is the observed count in row
, column
, and
is the expected count under independence. For a 2×2 table, the degrees of freedom is
.
Positive Predictive Value and the Wilson Score Interval
The Positive Predictive Value (PPV) is the proportion of positive test results that are true positives:

Because
is estimated from a finite sample, we quantify uncertainty using the Wilson score confidence interval. Unlike the naive normal approximation
which breaks down for proportions near zero or one, the Wilson interval centers around a adjusted proportion:

The Bayesian Engine (bayes.ss)
The module bayes.ss provides a general Bayesian inference engine. A Bayesian model is represented as an association list of (hypothesis . probability) pairs.
1 ;; File: bayes.ss
2 ;; Bayesian inference core.
3 ;;
4 ;; A Bayes model is simply a normalised alist of (hypothesis . probability).
5 ;; UPDATE applies Bayes' Theorem:
6 ;;
7 ;; P(H | E) = P(E | H) * P(H) / sum_h P(E | h) * P(h)
8
9 (export make-bayes-model update posterior posteriors maximum-a-posteriori)
10
11 ;; Sum a list of numbers (fold avoids apply's argument-count limit on big lists).
12 (def (sum xs) (foldl + 0 xs))
13
14 (def (sum-cdrs alist)
15 (sum (map cdr alist)))
16
17 ;; Create a Bayes model from PRIOR-ALIST, an alist of (HYPOTHESIS . PRIOR).
18 ;; Priors are automatically normalised so they sum to 1.
19 (def (make-bayes-model prior-alist)
20 (let ((total (sum-cdrs prior-alist)))
21 (when (zero? total)
22 (error "All priors are zero -- cannot normalise."))
23 (map (lambda (pair) (cons (car pair) (/ (cdr pair) total)))
24 prior-alist)))
25
26 ;; Return a new model with posteriors computed via Bayes' Theorem.
27 ;; EVIDENCE is an arbitrary datum passed to LIKELIHOOD-FN, a function of two
28 ;; arguments (HYPOTHESIS EVIDENCE) that returns P(evidence | hypothesis).
29 (def (update model evidence likelihood-fn)
30 (let* ((unnormalised
31 (map (lambda (pair)
32 (cons (car pair)
33 (* (likelihood-fn (car pair) evidence) (cdr pair))))
34 model))
35 (marginal (sum-cdrs unnormalised)))
36 (when (zero? marginal)
37 (error "Marginal likelihood is zero -- evidence is impossible under all hypotheses."))
38 (map (lambda (pair) (cons (car pair) (/ (cdr pair) marginal)))
39 unnormalised)))
40
41 ;; Return the posterior probability for HYPOTHESIS in MODEL.
42 (def (posterior model hypothesis)
43 (let ((entry (assoc hypothesis model)))
44 (if entry
45 (cdr entry)
46 (error "Hypothesis not found in model:" hypothesis))))
47
48 ;; Return the full posterior alist.
49 (def (posteriors model) model)
50
51 ;; Return (HYPOTHESIS . PROBABILITY) for the most probable hypothesis.
52 (def (maximum-a-posteriori model)
53 (foldl (lambda (pair best) (if (> (cdr pair) (cdr best)) pair best))
54 (car model)
55 (cdr model)))
In update, foldl is used to compute the marginal likelihood, safely handling arbitrarily large lists without hitting call stack limits.
Correlation Analysis (correlation.ss)
The module correlation.ss provides tools to evaluate association between variables, including Pearson product-moment correlation
and Spearman rank-order correlation
.
1 ;; File: correlation.ss
2 ;; Correlation helpers.
3 ;;
4 ;; NOTE: Correlation measures *association*, NOT causation.
5 ;; A high |r| between X and Y does not imply that X causes Y,
6 ;; that Y causes X, or even that they share a direct mechanism.
7
8 (import :std/sort)
9 (export mean std-dev rank-list pearson-r spearman-rho correlation-matrix)
10
11 ;; Sum a list of numbers (fold avoids apply's argument-count limit on big lists).
12 (def (sum xs) (foldl + 0 xs))
13
14 ;; Arithmetic mean of a list of numbers.
15 (def (mean xs)
16 (/ (sum xs) (length xs)))
17
18 ;; Population standard deviation of a list of numbers.
19 (def (std-dev xs)
20 (let ((m (mean xs)))
21 (sqrt (/ (sum (map (lambda (x) (expt (- x m) 2)) xs))
22 (length xs)))))
23
24 ;; Return a list of ranks (1-based, average ties) for XS.
25 (def (rank-list xs)
26 (let* ((n (length xs))
27 (indexed (let loop ((l xs) (i 0) (acc '()))
28 (if (null? l)
29 (reverse acc)
30 (loop (cdr l) (+ i 1) (cons (cons (car l) i) acc)))))
31 (sorted (list->vector (sort indexed (lambda (a b) (< (car a) (car b))))))
32 (ranks (make-vector n 0.0)))
33 ;; Walk the sorted vector, assigning the average rank to each tie group.
34 (let loop ((i 0))
35 (when (< i n)
36 (let find-end ((j i))
37 (if (and (< j n)
38 (= (car (vector-ref sorted j)) (car (vector-ref sorted i))))
39 (find-end (+ j 1))
40 ;; average of ranks (i+1)..j is (i+1+j)/2
41 (let ((avg (/ (+ i 1 j) 2.0)))
42 (do ((k i (+ k 1))) ((= k j))
43 (vector-set! ranks (cdr (vector-ref sorted k)) avg))
44 (loop j))))))
45 (vector->list ranks)))
46
47 ;; Pearson product-moment correlation coefficient.
48 ;; WARNING: measures linear association only -- not causation.
49 (def (pearson-r xs ys)
50 (unless (= (length xs) (length ys))
51 (error "XS and YS must have the same length."))
52 (let ((n (length xs))
53 (mx (mean xs))
54 (my (mean ys))
55 (sx (std-dev xs))
56 (sy (std-dev ys)))
57 (if (or (zero? sx) (zero? sy))
58 0.0 ; a constant variable has no correlation
59 (/ (sum (map (lambda (x y) (* (- x mx) (- y my))) xs ys))
60 (* n sx sy)))))
61
62 ;; Spearman rank-order correlation: Pearson r computed on ranks.
63 ;; WARNING: measures monotonic association only -- not causation.
64 (def (spearman-rho xs ys)
65 (pearson-r (rank-list xs) (rank-list ys)))
66
67 ;; Given DATA-ALIST of (NAME . VALUES-LIST) pairs, return a list of
68 ;; (NAME-A NAME-B . PEARSON-R) triples for all pairs.
69 (def (correlation-matrix data-alist)
70 (append-map
71 (lambda (a)
72 (map (lambda (b)
73 (cons (car a) (cons (car b) (pearson-r (cdr a) (cdr b)))))
74 data-alist))
75 data-alist))
76
77 (def (append-map f l) (apply append (map f l)))
The rank-list procedure properly handles tied values by assigning the average rank across all tied elements in the group, ensuring an unbiased Spearman correlation.
The Frequentist Toolkit (frequentist.ss)
The module frequentist.ss implements statistical hypothesis tests and probability distributions, including standard normal and chi-squared cumulative distribution functions, z-tests, and Wilson score intervals.
1 ;; File: frequentist.ss
2 ;; Frequentist hypothesis-testing toolkit: z-tests, chi-squared tests,
3 ;; and confidence intervals.
4
5 (export phi-approx chi-squared-cdf z-score z-test-proportion
6 chi-squared-test chi-squared-independence
7 z-critical confidence-interval-proportion)
8
9 ;; Sum a list of numbers (fold avoids apply's argument-count limit on big lists).
10 (def (sum xs) (foldl + 0 xs))
11
12 (def pi (* 4.0 (atan 1.0)))
13
14 ;; Approximate the standard normal CDF Phi(z) = P(Z <= z) using the
15 ;; Abramowitz & Stegun 26.2.17 polynomial (max abs error 7.5e-8).
16 (def (phi-approx z)
17 (let* ((p 0.2316419)
18 (b1 0.319381530)
19 (b2 -0.356563782)
20 (b3 1.781477937)
21 (b4 -1.821255978)
22 (b5 1.330274429)
23 (az (abs (exact->inexact z)))
24 (t (/ 1.0 (+ 1.0 (* p az))))
25 (pdf (/ (exp (* -0.5 az az)) (sqrt (* 2.0 pi))))
26 (cdf (- 1.0 (* pdf (+ (* b1 t)
27 (* b2 (expt t 2))
28 (* b3 (expt t 3))
29 (* b4 (expt t 4))
30 (* b5 (expt t 5)))))))
31 (if (>= z 0) cdf (- 1.0 cdf))))
32
33 ;; Approximate the chi-squared CDF P(X <= x) with DF degrees of freedom
34 ;; using the Wilson-Hilferty (1931) normal approximation.
35 (def (chi-squared-cdf x df)
36 (if (<= x 0)
37 0.0
38 (let* ((k (exact->inexact df))
39 (term (/ 2.0 (* 9.0 k)))
40 (z (/ (- (expt (/ x k) (/ 1.0 3.0)) (- 1.0 term))
41 (sqrt term))))
42 (phi-approx z))))
43
44 ;; Standard z-score: (OBSERVED - EXPECTED) / STD-DEV.
45 (def (z-score observed expected std-dev)
46 (unless (> std-dev 0) (error "STD-DEV must be positive."))
47 (/ (- observed expected) (exact->inexact std-dev)))
48
49 ;; One-sample two-tailed z-test for a binomial proportion.
50 ;; Tests H0: p = HYPOTHESISED-P. Returns two values: Z-SCORE and P-VALUE.
51 (def (z-test-proportion successes n hypothesised-p)
52 (let* ((p0 (exact->inexact hypothesised-p))
53 (p-hat (/ (exact->inexact successes) n))
54 (se (sqrt (/ (* p0 (- 1.0 p0)) n)))
55 (z (/ (- p-hat p0) se))
56 (p-val (* 2.0 (- 1.0 (phi-approx (abs z))))))
57 (values z (min p-val 1.0))))
58
59 ;; Pearson's chi-squared goodness-of-fit test.
60 ;; OBSERVED and EXPECTED are equal-length lists of counts.
61 ;; Returns three values: CHI-SQUARED, DF, and P-VALUE.
62 (def (chi-squared-test observed expected)
63 (unless (= (length observed) (length expected))
64 (error "OBSERVED and EXPECTED must have the same length."))
65 (let* ((chi2 (sum (map (lambda (o e)
66 (if (zero? e) 0.0
67 (/ (expt (- o e) 2) (exact->inexact e))))
68 observed expected)))
69 (df (- (length observed) 1))
70 (p-val (- 1.0 (chi-squared-cdf chi2 df))))
71 (values chi2 df (max p-val 0.0))))
72
73 ;; Pearson's chi-squared test of independence for a contingency TABLE
74 ;; (a list of rows, each a list of counts). Expected counts come from the
75 ;; row and column marginals, so DF = (rows - 1) * (cols - 1).
76 ;; Returns three values: CHI-SQUARED, DF, and P-VALUE.
77 (def (chi-squared-independence table)
78 (let ((rows (length table))
79 (cols (length (car table))))
80 (unless (and (>= rows 2) (>= cols 2))
81 (error "TABLE must have at least two rows and two columns."))
82 (let* ((row-totals (map (lambda (row) (sum row)) table))
83 (col-totals (apply map + table)) ; column-wise sums
84 (n (sum row-totals))
85 (chi2 (sum
86 (map (lambda (row row-total)
87 (sum
88 (map (lambda (o col-total)
89 (let ((e (/ (* row-total col-total)
90 (exact->inexact n))))
91 (if (zero? e) 0.0
92 (/ (expt (- o e) 2) e))))
93 row col-totals)))
94 table row-totals)))
95 (df (* (- rows 1) (- cols 1)))
96 (p-val (- 1.0 (chi-squared-cdf chi2 df))))
97 (values chi2 df (max p-val 0.0)))))
98
99 ;; Return the z* critical value for a two-sided confidence level.
100 (def (z-critical confidence)
101 (let ((entry (find (lambda (pair) (< (abs (- (car pair) confidence)) 1e-6))
102 '((0.90 . 1.6449) (0.95 . 1.9600) (0.99 . 2.5758)))))
103 (if entry
104 (cdr entry)
105 (let ((target (/ (+ 1.0 confidence) 2.0)))
106 (let loop ((i 0) (lo 0.0) (hi 5.0))
107 (if (= i 60)
108 (/ (+ lo hi) 2.0)
109 (let ((mid (/ (+ lo hi) 2.0)))
110 (if (< (phi-approx mid) target)
111 (loop (+ i 1) mid hi)
112 (loop (+ i 1) lo mid)))))))))
113
114 ;; Wilson score confidence interval for a binomial proportion.
115 ;; Returns two values: LOWER and UPPER bounds.
116 (def (confidence-interval-proportion successes n confidence: (confidence 0.95))
117 (let* ((n (exact->inexact n))
118 (p (/ successes n))
119 (z (z-critical confidence))
120 (z2 (* z z))
121 (denom (+ 1.0 (/ z2 n)))
122 (centre (/ (+ p (/ z2 (* 2.0 n))) denom))
123 (margin (/ (* z (sqrt (+ (/ (* p (- 1.0 p)) n)
124 (/ z2 (* 4.0 n n)))))
125 denom)))
126 (values (max 0.0 (- centre margin))
127 (min 1.0 (+ centre margin)))))
The functions z-test-proportion, chi-squared-test, chi-squared-independence, and confidence-interval-proportion return multiple values using Scheme’s values primitive, unpacked by callers using let-values.
The Medical Screening Example (medical.ss)
The module medical.ss models the 0.1% prevalence medical screening scenario using Bayesian updating and synthetic population correlation.
1 ;; File: medical.ss
2 ;; Medical-diagnosis worked example (Bayesian + correlation).
3
4 (import :std/format
5 "bayes" "correlation" "fmt")
6 (export prevalence sensitivity false-positive-rate
7 medical-likelihood run-bayesian-analysis
8 run-correlation-analysis run-medical-example)
9
10 (def prevalence 0.001) ; P(disease)
11 (def sensitivity 0.99) ; P(positive | disease)
12 (def false-positive-rate 0.05) ; P(positive | healthy)
13
14 ;; Return P(evidence | hypothesis). The evidence is always a positive test.
15 (def (medical-likelihood hypothesis evidence)
16 (case hypothesis
17 ((disease) sensitivity)
18 ((healthy) false-positive-rate)
19 (else (error "Unknown hypothesis" hypothesis))))
20
21 ;; Compute posterior probability of disease given a positive test.
22 (def (run-bayesian-analysis)
23 (let* ((prior (make-bayes-model `((disease . ,prevalence)
24 (healthy . ,(- 1.0 prevalence)))))
25 (updated (update prior 'positive-test medical-likelihood)))
26 (displayln "\n=== Bayesian Analysis: Medical Screening Test ===")
27 (displayln "Prior probabilities:")
28 (for-each (lambda (p) (printf " P(~a) = ~a\n" (car p) (fixed (cdr p) 4)))
29 (posteriors prior))
30 (displayln "\nAfter a POSITIVE test result:")
31 (for-each (lambda (p)
32 (printf " P(~a | positive) = ~a (~a)\n"
33 (car p) (fixed (cdr p) 4) (percent (cdr p))))
34 (posteriors updated))
35 (printf "\nMAP hypothesis: ~a\n" (car (maximum-a-posteriori updated)))
36 (displayln "\nKey insight: despite 99% sensitivity, a positive test")
37 (displayln "only yields about 1.9% probability of disease because the")
38 (displayln "disease is so rare (0.1% prevalence). This is exactly")
39 (displayln "the kind of counter-intuitive result Bayes' Theorem reveals.")
40 updated))
41
42 ;; Generate N individuals; return (TEST-RESULTS . ACTUAL-DIAGNOSES) as 0/1 lists.
43 (def (generate-synthetic-population (n 10000))
44 (let loop ((i 0) (tests '()) (diagnoses '()))
45 (if (= i n)
46 (cons tests diagnoses)
47 (let* ((has-disease (< (random-real) prevalence))
48 (test-positive (< (random-real)
49 (if has-disease sensitivity false-positive-rate))))
50 (loop (+ i 1)
51 (cons (if test-positive 1.0 0.0) tests)
52 (cons (if has-disease 1.0 0.0) diagnoses))))))
53
54 ;; Compute Pearson r between test results and actual disease status.
55 (def (run-correlation-analysis)
56 (let* ((pop (generate-synthetic-population 100000))
57 (tests (car pop))
58 (diagnoses (cdr pop))
59 (r (pearson-r tests diagnoses)))
60 (printf "\n=== Correlation Analysis (N = ~a) ===\n" (with-commas (length tests)))
61 (printf "Pearson r(test-result, disease) = ~a\n" (fixed r 4))
62 (displayln "\nThis positive correlation is real but modest. It shows")
63 (displayln "that the test result and disease status are associated,")
64 (displayln "but the correlation coefficient alone cannot tell you the")
65 (displayln "probability that any *individual* patient is sick -- that")
66 (displayln "requires Bayesian reasoning with the base rate (prevalence).")
67 r))
68
69 (def (run-medical-example)
70 (run-bayesian-analysis)
71 (run-correlation-analysis)
72 (displayln "\n=== Done. ==="))
The Frequentist Trial Simulation (frequentist-demo.ss)
The module frequentist-demo.ss runs a simulated clinical trial of 100,000 screened patients and analyzes the results using frequentist hypothesis tests:
1 ;; File: frequentist-demo.ss
2 ;; Re-examines the medical screening scenario from a frequentist standpoint:
3 ;; 1. Simulate a clinical trial (N = 100,000).
4 ;; 2. Chi-squared test of independence between test result and disease.
5 ;; 3. Wilson confidence interval for positive predictive value (PPV).
6 ;; 4. Z-test of the positive-test rate against prevalence.
7 ;; 5. Side-by-side comparison with the Bayesian posterior.
8
9 (import :std/format
10 "bayes" "frequentist" "medical" "fmt")
11 (export simulate-screening run-frequentist-demo)
12
13 ;; Simulate N individuals screened for the rare disease.
14 ;; Returns four values: TP FP TN FN.
15 (def (simulate-screening (n 100000))
16 (let loop ((i 0) (tp 0) (fp 0) (tn 0) (fn 0))
17 (if (= i n)
18 (values tp fp tn fn)
19 (let* ((sick (< (random-real) prevalence))
20 (pos (< (random-real) (if sick sensitivity false-positive-rate))))
21 (cond
22 ((and sick pos) (loop (+ i 1) (+ tp 1) fp tn fn))
23 (sick (loop (+ i 1) tp fp tn (+ fn 1)))
24 (pos (loop (+ i 1) tp (+ fp 1) tn fn))
25 (else (loop (+ i 1) tp fp (+ tn 1) fn)))))))
26
27 (def (format-p p)
28 (if (< p 1e-15) "< 1e-15 (essentially zero)" (format "= ~a" p)))
29
30 (def (run-frequentist-demo)
31 (displayln "\n================================================================")
32 (displayln " FREQUENTIST ANALYSIS: Medical Screening Test")
33 (displayln "================================================================")
34 (let-values (((tp fp tn fn) (simulate-screening 100000)))
35 (let ((n (+ tp fp tn fn))
36 (positives (+ tp fp)))
37 ;; 1. Simulation
38 (printf "\n--- 1. Simulated Clinical Trial (N = ~a) ---\n" (with-commas n))
39 (printf " True Positives (TP): ~a\n" tp)
40 (printf " False Positives (FP): ~a\n" fp)
41 (printf " True Negatives (TN): ~a\n" tn)
42 (printf " False Negatives (FN): ~a\n" fn)
43
44 ;; 2. Chi-squared test of independence
45 (displayln "\n--- 2. Chi-Squared Test of Independence ---")
46 (let-values (((chi2 df p-val)
47 (chi-squared-independence (list (list tp fp) (list fn tn)))))
48 (printf " chi-squared = ~a df = ~a p-value ~a\n"
49 (fixed chi2 2) df (format-p p-val))
50 (displayln "\n Interpretation: the test result and disease status")
51 (displayln " are NOT independent (we reject H0). But this only")
52 (displayln " means the *association exists* -- it says nothing about")
53 (displayln " how strong it is or what it means for one patient."))
54
55 ;; 3. Confidence interval for PPV
56 (let ((ppv (if (zero? positives) 0.0 (/ tp (exact->inexact positives)))))
57 (displayln "\n--- 3. Positive Predictive Value (PPV) ---")
58 (printf " PPV = TP / (TP + FP) = ~a / ~a = ~a (~a)\n"
59 tp positives (fixed ppv 4) (percent ppv))
60 (let-values (((lo hi) (confidence-interval-proportion tp positives
61 confidence: 0.95)))
62 (printf " 95% Wilson CI for PPV: [~a, ~a] (~a - ~a)\n"
63 (fixed lo 4) (fixed hi 4) (percent lo) (percent hi))))
64
65 ;; 4. Z-test: is the positive-test rate significantly > prevalence?
66 (displayln "\n--- 4. Z-Test: Positive Rate vs. Prevalence ---")
67 (let-values (((z p-val) (z-test-proportion positives n prevalence)))
68 (printf " Observed positive rate: ~a\n" (percent (/ positives (exact->inexact n)) 4))
69 (printf " Hypothesised rate (prevalence): ~a\n" (percent prevalence 4))
70 (printf " z = ~a p-value ~a\n" (fixed z 4) (format-p p-val))
71 (displayln "\n The positive rate far exceeds the disease prevalence")
72 (displayln " because of the 5% false-positive rate -- most positives")
73 (displayln " are healthy people."))
74
75 ;; 5. Contrast with the Bayesian result
76 (displayln "\n--- 5. Bayesian vs. Frequentist Side-by-Side ---")
77 (let* ((prior (make-bayes-model `((disease . ,prevalence)
78 (healthy . ,(- 1.0 prevalence)))))
79 (updated (update prior 'positive-test medical-likelihood))
80 (p-disease (posterior updated 'disease))
81 (ppv (/ tp (exact->inexact positives))))
82 (printf " Bayesian posterior P(disease | positive test) = ~a (~a)\n"
83 (fixed p-disease 4) (percent p-disease))
84 (printf " Frequentist PPV from simulation = ~a (~a)\n"
85 (fixed ppv 4) (percent ppv)))
86
87 (displayln "\n Both frameworks agree: a positive test on a rare disease")
88 (displayln " gives only about 2% probability of actual illness.")
89 (displayln "\n================================================================")
90 (displayln " Key lesson: statistical significance (small p-value) and")
91 (displayln " practical significance (high PPV) are different things.")
92 (displayln "================================================================"))))
Running the Code and Expected Output
Execute the complete probability suite using make test:
1 $ make test
2 gxi test.ss
3 === Sanity checks ===
4 [PASS] Phi(0) = 0.5
5 [PASS] Phi(1.96) ~ 0.975
6 [PASS] Pearson r of perfectly linear data = 1
7 [PASS] Spearman rho of monotonic non-linear data = 1
8 [PASS] rank-list averages ties
9 [PASS] chi-squared of perfect fit = 0
10
11 Correlation matrix example:
12 r(height, height) = 1.000
13 r(height, weight) = 0.997
14 r(height, shoe) = 0.000
15 r(weight, height) = 0.997
16 r(weight, weight) = 1.000
17 r(weight, shoe) = 0.043
18 r(shoe, height) = 0.000
19 r(shoe, weight) = 0.043
20 r(shoe, shoe) = 1.000
21
22 === Bayesian Analysis: Medical Screening Test ===
23 Prior probabilities:
24 P(disease) = 0.0010
25 P(healthy) = 0.9990
26
27 After a POSITIVE test result:
28 P(disease | positive) = 0.0194 (1.94%)
29 P(healthy | positive) = 0.9806 (98.06%)
30
31 MAP hypothesis: healthy
32
33 Key insight: despite 99% sensitivity, a positive test
34 only yields about 1.9% probability of disease because the
35 disease is so rare (0.1% prevalence). This is exactly
36 the kind of counter-intuitive result Bayes' Theorem reveals.
37
38 === Correlation Analysis (N = 100,000) ===
39 Pearson r(test-result, disease) = 0.1439
40
41 This positive correlation is real but modest. It shows
42 that the test result and disease status are associated,
43 but the correlation coefficient alone cannot tell you the
44 probability that any *individual* patient is sick -- that
45 requires Bayesian reasoning with the base rate (prevalence).
46
47 === Done. ===
48
49 ================================================================
50 FREQUENTIST ANALYSIS: Medical Screening Test
51 ================================================================
52
53 --- 1. Simulated Clinical Trial (N = 100,000) ---
54 True Positives (TP): 103
55 False Positives (FP): 4930
56 True Negatives (TN): 94967
57 False Negatives (FN): 0
58
59 --- 2. Chi-Squared Test of Independence ---
60 chi-squared = 1945.50 df = 1 p-value < 1e-15 (essentially zero)
61
62 Interpretation: the test result and disease status
63 are NOT independent (we reject H0). But this only
64 means the *association exists* -- it says nothing about
65 how strong it is or what it means for one patient.
66
67 --- 3. Positive Predictive Value (PPV) ---
68 PPV = TP / (TP + FP) = 103 / 5033 = 0.0205 (2.05%)
69 95% Wilson CI for PPV: [0.0169, 0.0248] (1.69% - 2.48%)
70
71 --- 4. Z-Test: Positive Rate vs. Prevalence ---
72 Observed positive rate: 5.0330%
73 Hypothesised rate (prevalence): 0.1000%
74 z = 493.5468 p-value < 1e-15 (essentially zero)
75
76 The positive rate far exceeds the disease prevalence
77 because of the 5% false-positive rate -- most positives
78 are healthy people.
79
80 --- 5. Bayesian vs. Frequentist Side-by-Side ---
81 Bayesian posterior P(disease | positive test) = 0.0194 (1.94%)
82 Frequentist PPV from simulation = 0.0205 (2.05%)
83
84 Both frameworks agree: a positive test on a rare disease
85 gives only about 2% probability of actual illness.
86
87 ================================================================
88 Key lesson: statistical significance (small p-value) and
89 practical significance (high PPV) are different things.
90 ================================================================
Interpreting the Results
The side-by-side output illustrates the core statistical lesson:
- Alignment Across Paradigms: The Bayesian posterior
matches the simulated empirical trial proportion
within sampling error. Both methods confirm that approximately 98% of people testing positive are actually healthy.
- The p-Value Fallacy: The chi-squared test of independence yields
with
. A scientific paper could truthfully report that the test result is correlated with disease status with extreme statistical significance. Yet for an individual patient, a positive test result only means a 2% chance of disease. Statistical significance detects the existence of a real relationship; it does not measure clinical certainty or high diagnostic utility.
- Correlation Bounds: The Pearson correlation between test result and diagnosis is
. Even though the test has 99% sensitivity, the low prevalence keeps overall linear correlation modest.
Wrap Up
In this chapter we built a complete statistical toolkit in Gerbil Scheme covering both Bayesian updating and frequentist hypothesis testing. By modeling medical screening through both lenses, we saw that Bayesian priors and frequentist sampling distributions represent two complementary mathematical views of the same reality. Understanding both paradigms prevents common pitfalls such as the base rate fallacy and the conflation of p-value significance with practical predictive value.
Optional Practice Problems
- Repeated Bayesian Testing: Use
bayes.ssto simulate a second independent test on the same patient. Assuming the second test has identical sensitivity and false-positive rates, compute the posterior probability after two consecutive positive test results. - Two-Sample Difference in Proportions: Implement
(z-test-proportions-two-sample x1 n1 x2 n2)infrequentist.ssusing pooled standard error to test whether two independent binomial populations differ significantly. - Bayes Factor Calculator: Add a function
(bayes-factor model h1 h2 evidence likelihood-fn)that computes the ratio of posterior odds to prior odds for two competing hypotheses.