DotProduct.lean
Lean 4 source, lean/DataMiningAsObservation/DotProduct.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.
/-
DotProduct.lean. Equation 0.1, the dot product and the cosine.
The dot product is symmetric and bilinear. The cosine, the dot product over the two
lengths, lies between minus one and one by Cauchy–Schwarz and is unchanged when either
vector is scaled by a positive factor, while the dot product itself scales with the
vector. That difference is the reader difference of chapter 3. A cosine reader has
declared length a nuisance, and a dot-product reader has not.
-/
import Mathlib
namespace DMO.DotProduct
open Finset
variable {n : ℕ}
/-- The cosine of equation 0.1. -/
noncomputable def cosine (x y : Fin n → ℝ) : ℝ :=
(x ⬝ᵥ y) / (Real.sqrt (x ⬝ᵥ x) * Real.sqrt (y ⬝ᵥ y))
/-- A vector's dot product with itself is nonnegative. -/
theorem self_nonneg (x : Fin n → ℝ) : 0 ≤ x ⬝ᵥ x :=
Finset.sum_nonneg fun i _ => mul_self_nonneg (x i)
/-- The dot product is symmetric. -/
theorem dot_comm (x y : Fin n → ℝ) : x ⬝ᵥ y = y ⬝ᵥ x := dotProduct_comm x y
/-- **Cauchy–Schwarz.** The square of the dot product is at most the product of the squared
lengths. -/
theorem dot_sq_le (x y : Fin n → ℝ) : (x ⬝ᵥ y) ^ 2 ≤ (x ⬝ᵥ x) * (y ⬝ᵥ y) := by
have h := Finset.sum_mul_sq_le_sq_mul_sq Finset.univ x y
simpa [dotProduct, sq] using h
/-- **The cosine lies between minus one and one.** -/
theorem cosine_mem (x y : Fin n → ℝ) : -1 ≤ cosine x y ∧ cosine x y ≤ 1 := by
unfold cosine
have hx : 0 ≤ x ⬝ᵥ x := self_nonneg x
have hden : Real.sqrt (x ⬝ᵥ x) * Real.sqrt (y ⬝ᵥ y) = Real.sqrt ((x ⬝ᵥ x) * (y ⬝ᵥ y)) := by
rw [Real.sqrt_mul hx]
rw [hden]
rcases eq_or_lt_of_le (Real.sqrt_nonneg ((x ⬝ᵥ x) * (y ⬝ᵥ y))) with h0 | hpos
· rw [← h0, div_zero]; norm_num
· have hcs : |x ⬝ᵥ y| ≤ Real.sqrt ((x ⬝ᵥ x) * (y ⬝ᵥ y)) := by
rw [← Real.sqrt_sq_eq_abs]
exact Real.sqrt_le_sqrt (dot_sq_le x y)
rw [abs_le] at hcs
constructor
· rw [le_div_iff₀ hpos]; linarith
· rw [div_le_one hpos]; exact hcs.2
/-- **The dot product reads length.** Scaling a vector scales its dot product. -/
theorem dot_smul (x y : Fin n → ℝ) (c : ℝ) : (c • x) ⬝ᵥ y = c * (x ⬝ᵥ y) := by
rw [smul_dotProduct, smul_eq_mul]
/-- **The cosine ignores length.** Scaling a vector by a positive factor leaves the cosine
unchanged. -/
theorem cosine_smul (x y : Fin n → ℝ) (c : ℝ) (hc : 0 < c) : cosine (c • x) y = cosine x y := by
unfold cosine
have h2 : (c • x) ⬝ᵥ (c • x) = c ^ 2 * (x ⬝ᵥ x) := by
rw [smul_dotProduct, dotProduct_smul, smul_eq_mul, smul_eq_mul]; ring
rw [dot_smul, h2, Real.sqrt_mul (by positivity), Real.sqrt_sq hc.le]
by_cases hx : Real.sqrt (x ⬝ᵥ x) = 0
· simp [hx]
· by_cases hy : Real.sqrt (y ⬝ᵥ y) = 0
· simp [hy]
· field_simp
end DMO.DotProduct