/-- Prove the shift identity `∑ (xᵢ − x̄)² = ∑ (xᵢ − c)² − n (x̄ − c)²`.
Hints: first show `∑ (xᵢ − c) = n (x̄ − c)` using `sum_eq_card_mul_mean`; then rewrite each
`(xᵢ − x̄)²` as `(xᵢ − c)² − 2 (x̄ − c)(xᵢ − c) + (x̄ − c)²` (`ring`) and split the sum with
`sum_add_distrib`, `sum_sub_distrib` and `mul_sum`. -/
theorem sum_sq_dev_eq {ι : Type*} (s : Finset ι) (x : ι → ℝ) (c : ℝ) :
∑ i ∈ s, (x i - sampleMean s x) ^ 2 =
∑ i ∈ s, (x i - c) ^ 2 - s.card * (sampleMean s x - c) ^ 2 := by
sorryShow the compiled solution
/-- **The shift identity.** For any number `c`,
`∑ (xᵢ − x̄)² = ∑ (xᵢ − c)² − n (x̄ − c)²`. In particular (taking `c` arbitrary) the sample
mean minimises `c ↦ ∑ (xᵢ − c)²`, and (taking `c = μ`) it is the key step in Bessel's
correction. Proof: expand `((xᵢ − c) − (x̄ − c))²` and use `∑ (xᵢ − c) = n (x̄ − c)`. -/
theorem sum_sq_dev_eq {ι : Type*} (s : Finset ι) (x : ι → ℝ) (c : ℝ) :
∑ i ∈ s, (x i - sampleMean s x) ^ 2 =
∑ i ∈ s, (x i - c) ^ 2 - s.card * (sampleMean s x - c) ^ 2 := by
set m := sampleMean s x
have hsum : ∑ i ∈ s, (x i - c) = s.card * (m - c) := by
rw [sum_sub_distrib, sum_eq_card_mul_mean s x, sum_const, nsmul_eq_mul]
ring
have hpt : ∀ i ∈ s, (x i - m) ^ 2 = (x i - c) ^ 2 - 2 * (m - c) * (x i - c) + (m - c) ^ 2 := by
intro i _
ring
rw [sum_congr rfl hpt, sum_add_distrib, sum_sub_distrib, ← mul_sum, hsum, sum_const,
nsmul_eq_mul]
ringAxioms used: propext, Classical.choice, Quot.soundformal/Lumenary/Statistics.leanTry it in the Lean web editor