import OAI.Combinatorics.ContingencyTables.Transport.RationalRootBisection import OAI.Combinatorics.MatchingCount.Arithmetic.TreeFraction namespace OAI /-! # Integer implementation of the correction-root bisection The two interval endpoints share one dyadic denominator. Every comparison is an inequality between natural powers and products. This is the literal integer algorithm to which the rational correction analysis is applied. -/ namespace ContingencyTables.DyadicRootBisection open MatchingFPRAS abbrev State := (ℕ×ℕ)×ℕ def value (z : State) : ℚ×ℚ := ((z.1.1:ℚ)/z.2,(z.1.2:ℚ)/z.2) def advance (c : TreeFraction.Fraction) (s : ℕ) (z : State) : State := if (z.1.1+z.1.2)^s*c.2 ≤ c.1*(2*z.2)^s then ((z.1.1+z.1.2,2*z.1.2),2*z.2) else ((2*z.1.1,z.1.1+z.1.2),2*z.2) def run (c : TreeFraction.Fraction) (s : ℕ) : ℕ→State | 0=>((0,8),1) | n+1=>advance c s (run c s n) def output (c : TreeFraction.Fraction) (s n : ℕ) : TreeFraction.Fraction := let z:=run c s n TreeFraction.normalize (z.1.1+z.1.2,2*z.2) lemma compare_iff (a d p q s : ℕ) (hd : 0 rfl lemma run_denominator (c : TreeFraction.Fraction) (s n : ℕ) : (run c s n).2=2^n := by induction n with | zero=>rfl | succ n ih=>simp only [run,advance_denominator,ih,pow_succ,mul_comm] lemma advance_bounds (c : TreeFraction.Fraction) (s : ℕ) (z : State) (ha : z.1.1≤8*z.2) (hb : z.1.2≤8*z.2) : (advance c s z).1.1≤8*(advance c s z).2 ∧ (advance c s z).1.2≤8*(advance c s z).2 := by unfold advance split_ifs <;> dsimp only <;> omega lemma run_bounds (c : TreeFraction.Fraction) (s n : ℕ) : (run c s n).1.1≤8*2^n ∧ (run c s n).1.2≤8*2^n := by induction n with | zero=>norm_num [run] | succ n ih=> have h:=advance_bounds c s (run c s n) (by simpa only [run_denominator] using ih.1) (by simpa only [run_denominator] using ih.2) change (run c s (n+1)).1.1≤8*(run c s (n+1)).2 ∧ (run c s (n+1)).1.2≤8*(run c s (n+1)).2 at h simpa only [run_denominator] using h lemma value_advance (c : TreeFraction.Fraction) (hc : 0norm_num [run,value,RationalRootBisection.interval] | succ n ih=> rw [run,value_advance c hc s _ (by rw [run_denominator]; positivity),ih] rfl theorem output_value (c : TreeFraction.Fraction) (hc : 0