src/HOL/Decision_Procs/Approximation.thy
author nipkow
Mon Dec 06 19:18:02 2010 +0100 (2010-12-06)
changeset 41022 81d337539d57
parent 40892 6f7292b94652
child 41024 ba961a606c67
permissions -rw-r--r--
moved coercion decl. for int
     1 (* Author:     Johannes Hoelzl, TU Muenchen
     2    Coercions removed by Dmitriy Traytel *)
     3 
     4 header {* Prove Real Valued Inequalities by Computation *}
     5 
     6 theory Approximation
     7 imports Complex_Main Float Reflection "~~/src/HOL/Decision_Procs/Dense_Linear_Order" Efficient_Nat
     8 begin
     9 
    10 declare [[coercion_map map]]
    11 declare [[coercion_map "% f g h . g o h o f"]]
    12 declare [[coercion_map "% f g (x,y) . (f x, g y)"]]
    13 declare [[coercion "% x . Float x 0"]]
    14 declare [[coercion "real::float\<Rightarrow>real"]]
    15 
    16 section "Horner Scheme"
    17 
    18 subsection {* Define auxiliary helper @{text horner} function *}
    19 
    20 primrec horner :: "(nat \<Rightarrow> nat) \<Rightarrow> (nat \<Rightarrow> nat \<Rightarrow> nat) \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> real \<Rightarrow> real" where
    21 "horner F G 0 i k x       = 0" |
    22 "horner F G (Suc n) i k x = 1 / k - x * horner F G n (F i) (G i k) x"
    23 
    24 lemma horner_schema': fixes x :: real  and a :: "nat \<Rightarrow> real"
    25   shows "a 0 - x * (\<Sum> i=0..<n. (-1)^i * a (Suc i) * x^i) = (\<Sum> i=0..<Suc n. (-1)^i * a i * x^i)"
    26 proof -
    27   have shift_pow: "\<And>i. - (x * ((-1)^i * a (Suc i) * x ^ i)) = (-1)^(Suc i) * a (Suc i) * x ^ (Suc i)" by auto
    28   show ?thesis unfolding setsum_right_distrib shift_pow diff_minus setsum_negf[symmetric] setsum_head_upt_Suc[OF zero_less_Suc]
    29     setsum_reindex[OF inj_Suc, unfolded comp_def, symmetric, of "\<lambda> n. (-1)^n  *a n * x^n"] by auto
    30 qed
    31 
    32 lemma horner_schema: fixes f :: "nat \<Rightarrow> nat" and G :: "nat \<Rightarrow> nat \<Rightarrow> nat" and F :: "nat \<Rightarrow> nat"
    33   assumes f_Suc: "\<And>n. f (Suc n) = G ((F ^^ n) s) (f n)"
    34   shows "horner F G n ((F ^^ j') s) (f j') x = (\<Sum> j = 0..< n. -1 ^ j * (1 / (f (j' + j))) * x ^ j)"
    35 proof (induct n arbitrary: i k j')
    36   case (Suc n)
    37 
    38   show ?case unfolding horner.simps Suc[where j'="Suc j'", unfolded funpow.simps comp_def f_Suc]
    39     using horner_schema'[of "\<lambda> j. 1 / (f (j' + j))"] by auto
    40 qed auto
    41 
    42 lemma horner_bounds':
    43   fixes lb :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> float \<Rightarrow> float" and ub :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> float \<Rightarrow> float"
    44   assumes "0 \<le> real x" and f_Suc: "\<And>n. f (Suc n) = G ((F ^^ n) s) (f n)"
    45   and lb_0: "\<And> i k x. lb 0 i k x = 0"
    46   and lb_Suc: "\<And> n i k x. lb (Suc n) i k x = lapprox_rat prec 1 k - x * (ub n (F i) (G i k) x)"
    47   and ub_0: "\<And> i k x. ub 0 i k x = 0"
    48   and ub_Suc: "\<And> n i k x. ub (Suc n) i k x = rapprox_rat prec 1 k - x * (lb n (F i) (G i k) x)"
    49   shows "(lb n ((F ^^ j') s) (f j') x) \<le> horner F G n ((F ^^ j') s) (f j') x \<and>
    50          horner F G n ((F ^^ j') s) (f j') x \<le> (ub n ((F ^^ j') s) (f j') x)"
    51   (is "?lb n j' \<le> ?horner n j' \<and> ?horner n j' \<le> ?ub n j'")
    52 proof (induct n arbitrary: j')
    53   case 0 thus ?case unfolding lb_0 ub_0 horner.simps by auto
    54 next
    55   case (Suc n)
    56   have "?lb (Suc n) j' \<le> ?horner (Suc n) j'" unfolding lb_Suc ub_Suc horner.simps real_of_float_sub diff_minus
    57   proof (rule add_mono)
    58     show "(lapprox_rat prec 1 (f j')) \<le> 1 / (f j')" using lapprox_rat[of prec 1  "f j'"] by auto
    59     from Suc[where j'="Suc j'", unfolded funpow.simps comp_def f_Suc, THEN conjunct2] `0 \<le> real x`
    60     show "- real (x * ub n (F ((F ^^ j') s)) (G ((F ^^ j') s) (f j')) x) \<le>
    61           - (x * horner F G n (F ((F ^^ j') s)) (G ((F ^^ j') s) (f j')) x)"
    62       unfolding real_of_float_mult neg_le_iff_le by (rule mult_left_mono)
    63   qed
    64   moreover have "?horner (Suc n) j' \<le> ?ub (Suc n) j'" unfolding ub_Suc ub_Suc horner.simps real_of_float_sub diff_minus
    65   proof (rule add_mono)
    66     show "1 / (f j') \<le> (rapprox_rat prec 1 (f j'))" using rapprox_rat[of 1 "f j'" prec] by auto
    67     from Suc[where j'="Suc j'", unfolded funpow.simps comp_def f_Suc, THEN conjunct1] `0 \<le> real x`
    68     show "- (x * horner F G n (F ((F ^^ j') s)) (G ((F ^^ j') s) (f j')) x) \<le>
    69           - real (x * lb n (F ((F ^^ j') s)) (G ((F ^^ j') s) (f j')) x)"
    70       unfolding real_of_float_mult neg_le_iff_le by (rule mult_left_mono)
    71   qed
    72   ultimately show ?case by blast
    73 qed
    74 
    75 subsection "Theorems for floating point functions implementing the horner scheme"
    76 
    77 text {*
    78 
    79 Here @{term_type "f :: nat \<Rightarrow> nat"} is the sequence defining the Taylor series, the coefficients are
    80 all alternating and reciprocs. We use @{term G} and @{term F} to describe the computation of @{term f}.
    81 
    82 *}
    83 
    84 lemma horner_bounds: fixes F :: "nat \<Rightarrow> nat" and G :: "nat \<Rightarrow> nat \<Rightarrow> nat"
    85   assumes "0 \<le> real x" and f_Suc: "\<And>n. f (Suc n) = G ((F ^^ n) s) (f n)"
    86   and lb_0: "\<And> i k x. lb 0 i k x = 0"
    87   and lb_Suc: "\<And> n i k x. lb (Suc n) i k x = lapprox_rat prec 1 k - x * (ub n (F i) (G i k) x)"
    88   and ub_0: "\<And> i k x. ub 0 i k x = 0"
    89   and ub_Suc: "\<And> n i k x. ub (Suc n) i k x = rapprox_rat prec 1 k - x * (lb n (F i) (G i k) x)"
    90   shows "(lb n ((F ^^ j') s) (f j') x) \<le> (\<Sum>j=0..<n. -1 ^ j * (1 / (f (j' + j))) * (x ^ j))" (is "?lb") and
    91     "(\<Sum>j=0..<n. -1 ^ j * (1 / (f (j' + j))) * (x ^ j)) \<le> (ub n ((F ^^ j') s) (f j') x)" (is "?ub")
    92 proof -
    93   have "?lb  \<and> ?ub"
    94     using horner_bounds'[where lb=lb, OF `0 \<le> real x` f_Suc lb_0 lb_Suc ub_0 ub_Suc]
    95     unfolding horner_schema[where f=f, OF f_Suc] .
    96   thus "?lb" and "?ub" by auto
    97 qed
    98 
    99 lemma horner_bounds_nonpos: fixes F :: "nat \<Rightarrow> nat" and G :: "nat \<Rightarrow> nat \<Rightarrow> nat"
   100   assumes "real x \<le> 0" and f_Suc: "\<And>n. f (Suc n) = G ((F ^^ n) s) (f n)"
   101   and lb_0: "\<And> i k x. lb 0 i k x = 0"
   102   and lb_Suc: "\<And> n i k x. lb (Suc n) i k x = lapprox_rat prec 1 k + x * (ub n (F i) (G i k) x)"
   103   and ub_0: "\<And> i k x. ub 0 i k x = 0"
   104   and ub_Suc: "\<And> n i k x. ub (Suc n) i k x = rapprox_rat prec 1 k + x * (lb n (F i) (G i k) x)"
   105   shows "(lb n ((F ^^ j') s) (f j') x) \<le> (\<Sum>j=0..<n. (1 / (f (j' + j))) * real x ^ j)" (is "?lb") and
   106     "(\<Sum>j=0..<n. (1 / (f (j' + j))) * real x ^ j) \<le> (ub n ((F ^^ j') s) (f j') x)" (is "?ub")
   107 proof -
   108   { fix x y z :: float have "x - y * z = x + - y * z"
   109       by (cases x, cases y, cases z, simp add: plus_float.simps minus_float_def uminus_float.simps times_float.simps algebra_simps)
   110   } note diff_mult_minus = this
   111 
   112   { fix x :: float have "- (- x) = x" by (cases x, auto simp add: uminus_float.simps) } note minus_minus = this
   113 
   114   have move_minus: "(-x) = -1 * real x" by auto (* coercion "inside" is necessary *)
   115 
   116   have sum_eq: "(\<Sum>j=0..<n. (1 / (f (j' + j))) * real x ^ j) =
   117     (\<Sum>j = 0..<n. -1 ^ j * (1 / (f (j' + j))) * real (- x) ^ j)"
   118   proof (rule setsum_cong, simp)
   119     fix j assume "j \<in> {0 ..< n}"
   120     show "1 / (f (j' + j)) * real x ^ j = -1 ^ j * (1 / (f (j' + j))) * real (- x) ^ j"
   121       unfolding move_minus power_mult_distrib mult_assoc[symmetric]
   122       unfolding mult_commute unfolding mult_assoc[of "-1 ^ j", symmetric] power_mult_distrib[symmetric]
   123       by auto
   124   qed
   125 
   126   have "0 \<le> real (-x)" using assms by auto
   127   from horner_bounds[where G=G and F=F and f=f and s=s and prec=prec
   128     and lb="\<lambda> n i k x. lb n i k (-x)" and ub="\<lambda> n i k x. ub n i k (-x)", unfolded lb_Suc ub_Suc diff_mult_minus,
   129     OF this f_Suc lb_0 refl ub_0 refl]
   130   show "?lb" and "?ub" unfolding minus_minus sum_eq
   131     by auto
   132 qed
   133 
   134 subsection {* Selectors for next even or odd number *}
   135 
   136 text {*
   137 
   138 The horner scheme computes alternating series. To get the upper and lower bounds we need to
   139 guarantee to access a even or odd member. To do this we use @{term get_odd} and @{term get_even}.
   140 
   141 *}
   142 
   143 definition get_odd :: "nat \<Rightarrow> nat" where
   144   "get_odd n = (if odd n then n else (Suc n))"
   145 
   146 definition get_even :: "nat \<Rightarrow> nat" where
   147   "get_even n = (if even n then n else (Suc n))"
   148 
   149 lemma get_odd[simp]: "odd (get_odd n)" unfolding get_odd_def by (cases "odd n", auto)
   150 lemma get_even[simp]: "even (get_even n)" unfolding get_even_def by (cases "even n", auto)
   151 lemma get_odd_ex: "\<exists> k. Suc k = get_odd n \<and> odd (Suc k)"
   152 proof (cases "odd n")
   153   case True hence "0 < n" by (rule odd_pos)
   154   from gr0_implies_Suc[OF this] obtain k where "Suc k = n" by auto
   155   thus ?thesis unfolding get_odd_def if_P[OF True] using True[unfolded `Suc k = n`[symmetric]] by blast
   156 next
   157   case False hence "odd (Suc n)" by auto
   158   thus ?thesis unfolding get_odd_def if_not_P[OF False] by blast
   159 qed
   160 
   161 lemma get_even_double: "\<exists>i. get_even n = 2 * i" using get_even[unfolded even_mult_two_ex] .
   162 lemma get_odd_double: "\<exists>i. get_odd n = 2 * i + 1" using get_odd[unfolded odd_Suc_mult_two_ex] by auto
   163 
   164 section "Power function"
   165 
   166 definition float_power_bnds :: "nat \<Rightarrow> float \<Rightarrow> float \<Rightarrow> float * float" where
   167 "float_power_bnds n l u = (if odd n \<or> 0 < l then (l ^ n, u ^ n)
   168                       else if u < 0         then (u ^ n, l ^ n)
   169                                             else (0, (max (-l) u) ^ n))"
   170 
   171 lemma float_power_bnds: fixes x :: real
   172   assumes "(l1, u1) = float_power_bnds n l u" and "x \<in> {l .. u}"
   173   shows "x ^ n \<in> {l1..u1}"
   174 proof (cases "even n")
   175   case True
   176   show ?thesis
   177   proof (cases "0 < l")
   178     case True hence "odd n \<or> 0 < l" and "0 \<le> real l" unfolding less_float_def by auto
   179     have u1: "u1 = u ^ n" and l1: "l1 = l ^ n" using assms unfolding float_power_bnds_def if_P[OF `odd n \<or> 0 < l`] by auto
   180     have "real l ^ n \<le> x ^ n" and "x ^ n \<le> real u ^ n " using `0 \<le> real l` and assms unfolding atLeastAtMost_iff using power_mono[of l x] power_mono[of x u] by auto
   181     thus ?thesis using assms `0 < l` unfolding atLeastAtMost_iff l1 u1 float_power less_float_def by auto
   182   next
   183     case False hence P: "\<not> (odd n \<or> 0 < l)" using `even n` by auto
   184     show ?thesis
   185     proof (cases "u < 0")
   186       case True hence "0 \<le> - real u" and "- real u \<le> - x" and "0 \<le> - x" and "-x \<le> - real l" using assms unfolding less_float_def by auto
   187       hence "real u ^ n \<le> x ^ n" and "x ^ n \<le> real l ^ n" using power_mono[of  "-x" "-real l" n] power_mono[of "-real u" "-x" n]
   188         unfolding power_minus_even[OF `even n`] by auto
   189       moreover have u1: "u1 = l ^ n" and l1: "l1 = u ^ n" using assms unfolding float_power_bnds_def if_not_P[OF P] if_P[OF True] by auto
   190       ultimately show ?thesis using float_power by auto
   191     next
   192       case False
   193       have "\<bar>x\<bar> \<le> real (max (-l) u)"
   194       proof (cases "-l \<le> u")
   195         case True thus ?thesis unfolding max_def if_P[OF True] using assms unfolding le_float_def by auto
   196       next
   197         case False thus ?thesis unfolding max_def if_not_P[OF False] using assms unfolding le_float_def by auto
   198       qed
   199       hence x_abs: "\<bar>x\<bar> \<le> \<bar>real (max (-l) u)\<bar>" by auto
   200       have u1: "u1 = (max (-l) u) ^ n" and l1: "l1 = 0" using assms unfolding float_power_bnds_def if_not_P[OF P] if_not_P[OF False] by auto
   201       show ?thesis unfolding atLeastAtMost_iff l1 u1 float_power using zero_le_even_power[OF `even n`] power_mono_even[OF `even n` x_abs] by auto
   202     qed
   203   qed
   204 next
   205   case False hence "odd n \<or> 0 < l" by auto
   206   have u1: "u1 = u ^ n" and l1: "l1 = l ^ n" using assms unfolding float_power_bnds_def if_P[OF `odd n \<or> 0 < l`] by auto
   207   have "real l ^ n \<le> x ^ n" and "x ^ n \<le> real u ^ n " using assms unfolding atLeastAtMost_iff using power_mono_odd[OF False] by auto
   208   thus ?thesis unfolding atLeastAtMost_iff l1 u1 float_power less_float_def by auto
   209 qed
   210 
   211 lemma bnds_power: "\<forall> (x::real) l u. (l1, u1) = float_power_bnds n l u \<and> x \<in> {l .. u} \<longrightarrow> l1 \<le> x ^ n \<and> x ^ n \<le> u1"
   212   using float_power_bnds by auto
   213 
   214 section "Square root"
   215 
   216 text {*
   217 
   218 The square root computation is implemented as newton iteration. As first first step we use the
   219 nearest power of two greater than the square root.
   220 
   221 *}
   222 
   223 fun sqrt_iteration :: "nat \<Rightarrow> nat \<Rightarrow> float \<Rightarrow> float" where
   224 "sqrt_iteration prec 0 (Float m e) = Float 1 ((e + bitlen m) div 2 + 1)" |
   225 "sqrt_iteration prec (Suc m) x = (let y = sqrt_iteration prec m x
   226                                   in Float 1 -1 * (y + float_divr prec x y))"
   227 
   228 function ub_sqrt lb_sqrt :: "nat \<Rightarrow> float \<Rightarrow> float" where
   229 "ub_sqrt prec x = (if 0 < x then (sqrt_iteration prec prec x)
   230               else if x < 0 then - lb_sqrt prec (- x)
   231                             else 0)" |
   232 "lb_sqrt prec x = (if 0 < x then (float_divl prec x (sqrt_iteration prec prec x))
   233               else if x < 0 then - ub_sqrt prec (- x)
   234                             else 0)"
   235 by pat_completeness auto
   236 termination by (relation "measure (\<lambda> v. let (prec, x) = sum_case id id v in (if x < 0 then 1 else 0))", auto simp add: less_float_def)
   237 
   238 declare lb_sqrt.simps[simp del]
   239 declare ub_sqrt.simps[simp del]
   240 
   241 lemma sqrt_ub_pos_pos_1:
   242   assumes "sqrt x < b" and "0 < b" and "0 < x"
   243   shows "sqrt x < (b + x / b)/2"
   244 proof -
   245   from assms have "0 < (b - sqrt x) ^ 2 " by simp
   246   also have "\<dots> = b ^ 2 - 2 * b * sqrt x + (sqrt x) ^ 2" by algebra
   247   also have "\<dots> = b ^ 2 - 2 * b * sqrt x + x" using assms by (simp add: real_sqrt_pow2)
   248   finally have "0 < b ^ 2 - 2 * b * sqrt x + x" by assumption
   249   hence "0 < b / 2 - sqrt x + x / (2 * b)" using assms
   250     by (simp add: field_simps power2_eq_square)
   251   thus ?thesis by (simp add: field_simps)
   252 qed
   253 
   254 lemma sqrt_iteration_bound: assumes "0 < real x"
   255   shows "sqrt x < (sqrt_iteration prec n x)"
   256 proof (induct n)
   257   case 0
   258   show ?case
   259   proof (cases x)
   260     case (Float m e)
   261     hence "0 < m" using float_pos_m_pos[unfolded less_float_def] assms by auto
   262     hence "0 < sqrt m" by auto
   263 
   264     have int_nat_bl: "(nat (bitlen m)) = bitlen m" using bitlen_ge0 by auto
   265 
   266     have "x = (m / 2^nat (bitlen m)) * pow2 (e + (nat (bitlen m)))"
   267       unfolding pow2_add pow2_int Float real_of_float_simp by auto
   268     also have "\<dots> < 1 * pow2 (e + nat (bitlen m))"
   269     proof (rule mult_strict_right_mono, auto)
   270       show "real m < 2^nat (bitlen m)" using bitlen_bounds[OF `0 < m`, THEN conjunct2]
   271         unfolding real_of_int_less_iff[of m, symmetric] by auto
   272     qed
   273     finally have "sqrt x < sqrt (pow2 (e + bitlen m))" unfolding int_nat_bl by auto
   274     also have "\<dots> \<le> pow2 ((e + bitlen m) div 2 + 1)"
   275     proof -
   276       let ?E = "e + bitlen m"
   277       have E_mod_pow: "pow2 (?E mod 2) < 4"
   278       proof (cases "?E mod 2 = 1")
   279         case True thus ?thesis by auto
   280       next
   281         case False
   282         have "0 \<le> ?E mod 2" by auto
   283         have "?E mod 2 < 2" by auto
   284         from this[THEN zless_imp_add1_zle]
   285         have "?E mod 2 \<le> 0" using False by auto
   286         from xt1(5)[OF `0 \<le> ?E mod 2` this]
   287         show ?thesis by auto
   288       qed
   289       hence "sqrt (pow2 (?E mod 2)) < sqrt (2 * 2)" by auto
   290       hence E_mod_pow: "sqrt (pow2 (?E mod 2)) < 2" unfolding real_sqrt_abs2 by auto
   291 
   292       have E_eq: "pow2 ?E = pow2 (?E div 2 + ?E div 2 + ?E mod 2)" by auto
   293       have "sqrt (pow2 ?E) = sqrt (pow2 (?E div 2) * pow2 (?E div 2) * pow2 (?E mod 2))"
   294         unfolding E_eq unfolding pow2_add ..
   295       also have "\<dots> = pow2 (?E div 2) * sqrt (pow2 (?E mod 2))"
   296         unfolding real_sqrt_mult[of _ "pow2 (?E mod 2)"] real_sqrt_abs2 by auto
   297       also have "\<dots> < pow2 (?E div 2) * 2"
   298         by (rule mult_strict_left_mono, auto intro: E_mod_pow)
   299       also have "\<dots> = pow2 (?E div 2 + 1)" unfolding zadd_commute[of _ 1] pow2_add1 by auto
   300       finally show ?thesis by auto
   301     qed
   302     finally show ?thesis
   303       unfolding Float sqrt_iteration.simps real_of_float_simp by auto
   304   qed
   305 next
   306   case (Suc n)
   307   let ?b = "sqrt_iteration prec n x"
   308   have "0 < sqrt x" using `0 < real x` by auto
   309   also have "\<dots> < real ?b" using Suc .
   310   finally have "sqrt x < (?b + x / ?b)/2" using sqrt_ub_pos_pos_1[OF Suc _ `0 < real x`] by auto
   311   also have "\<dots> \<le> (?b + (float_divr prec x ?b))/2" by (rule divide_right_mono, auto simp add: float_divr)
   312   also have "\<dots> = (Float 1 -1) * (?b + (float_divr prec x ?b))" by auto
   313   finally show ?case unfolding sqrt_iteration.simps Let_def real_of_float_mult real_of_float_add right_distrib .
   314 qed
   315 
   316 lemma sqrt_iteration_lower_bound: assumes "0 < real x"
   317   shows "0 < real (sqrt_iteration prec n x)" (is "0 < ?sqrt")
   318 proof -
   319   have "0 < sqrt x" using assms by auto
   320   also have "\<dots> < ?sqrt" using sqrt_iteration_bound[OF assms] .
   321   finally show ?thesis .
   322 qed
   323 
   324 lemma lb_sqrt_lower_bound: assumes "0 \<le> real x"
   325   shows "0 \<le> real (lb_sqrt prec x)"
   326 proof (cases "0 < x")
   327   case True hence "0 < real x" and "0 \<le> x" using `0 \<le> real x` unfolding less_float_def le_float_def by auto
   328   hence "0 < sqrt_iteration prec prec x" unfolding less_float_def using sqrt_iteration_lower_bound by auto
   329   hence "0 \<le> real (float_divl prec x (sqrt_iteration prec prec x))" using float_divl_lower_bound[OF `0 \<le> x`] unfolding le_float_def by auto
   330   thus ?thesis unfolding lb_sqrt.simps using True by auto
   331 next
   332   case False with `0 \<le> real x` have "real x = 0" unfolding less_float_def by auto
   333   thus ?thesis unfolding lb_sqrt.simps less_float_def by auto
   334 qed
   335 
   336 lemma bnds_sqrt':
   337   shows "sqrt x \<in> {(lb_sqrt prec x) .. (ub_sqrt prec x) }"
   338 proof -
   339   { fix x :: float assume "0 < x"
   340     hence "0 < real x" and "0 \<le> real x" unfolding less_float_def by auto
   341     hence sqrt_gt0: "0 < sqrt x" by auto
   342     hence sqrt_ub: "sqrt x < sqrt_iteration prec prec x" using sqrt_iteration_bound by auto
   343 
   344     have "(float_divl prec x (sqrt_iteration prec prec x)) \<le>
   345           x / (sqrt_iteration prec prec x)" by (rule float_divl)
   346     also have "\<dots> < x / sqrt x"
   347       by (rule divide_strict_left_mono[OF sqrt_ub `0 < real x`
   348                mult_pos_pos[OF order_less_trans[OF sqrt_gt0 sqrt_ub] sqrt_gt0]])
   349     also have "\<dots> = sqrt x"
   350       unfolding inverse_eq_iff_eq[of _ "sqrt x", symmetric]
   351                 sqrt_divide_self_eq[OF `0 \<le> real x`, symmetric] by auto
   352     finally have "lb_sqrt prec x \<le> sqrt x"
   353       unfolding lb_sqrt.simps if_P[OF `0 < x`] by auto }
   354   note lb = this
   355 
   356   { fix x :: float assume "0 < x"
   357     hence "0 < real x" unfolding less_float_def by auto
   358     hence "0 < sqrt x" by auto
   359     hence "sqrt x < sqrt_iteration prec prec x"
   360       using sqrt_iteration_bound by auto
   361     hence "sqrt x \<le> ub_sqrt prec x"
   362       unfolding ub_sqrt.simps if_P[OF `0 < x`] by auto }
   363   note ub = this
   364 
   365   show ?thesis
   366   proof (cases "0 < x")
   367     case True with lb ub show ?thesis by auto
   368   next case False show ?thesis
   369   proof (cases "real x = 0")
   370     case True thus ?thesis
   371       by (auto simp add: less_float_def lb_sqrt.simps ub_sqrt.simps)
   372   next
   373     case False with `\<not> 0 < x` have "x < 0" and "0 < -x"
   374       by (auto simp add: less_float_def)
   375 
   376     with `\<not> 0 < x`
   377     show ?thesis using lb[OF `0 < -x`] ub[OF `0 < -x`]
   378       by (auto simp add: real_sqrt_minus lb_sqrt.simps ub_sqrt.simps)
   379   qed qed
   380 qed
   381 
   382 lemma bnds_sqrt: "\<forall> (x::real) lx ux. (l, u) = (lb_sqrt prec lx, ub_sqrt prec ux) \<and> x \<in> {lx .. ux} \<longrightarrow> l \<le> sqrt x \<and> sqrt x \<le> u"
   383 proof ((rule allI) +, rule impI, erule conjE, rule conjI)
   384   fix x :: real fix lx ux
   385   assume "(l, u) = (lb_sqrt prec lx, ub_sqrt prec ux)"
   386     and x: "x \<in> {lx .. ux}"
   387   hence l: "l = lb_sqrt prec lx " and u: "u = ub_sqrt prec ux" by auto
   388 
   389   have "sqrt lx \<le> sqrt x" using x by auto
   390   from order_trans[OF _ this]
   391   show "l \<le> sqrt x" unfolding l using bnds_sqrt'[of lx prec] by auto
   392 
   393   have "sqrt x \<le> sqrt ux" using x by auto
   394   from order_trans[OF this]
   395   show "sqrt x \<le> u" unfolding u using bnds_sqrt'[of ux prec] by auto
   396 qed
   397 
   398 section "Arcus tangens and \<pi>"
   399 
   400 subsection "Compute arcus tangens series"
   401 
   402 text {*
   403 
   404 As first step we implement the computation of the arcus tangens series. This is only valid in the range
   405 @{term "{-1 :: real .. 1}"}. This is used to compute \<pi> and then the entire arcus tangens.
   406 
   407 *}
   408 
   409 fun ub_arctan_horner :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> float \<Rightarrow> float"
   410 and lb_arctan_horner :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> float \<Rightarrow> float" where
   411   "ub_arctan_horner prec 0 k x = 0"
   412 | "ub_arctan_horner prec (Suc n) k x =
   413     (rapprox_rat prec 1 k) - x * (lb_arctan_horner prec n (k + 2) x)"
   414 | "lb_arctan_horner prec 0 k x = 0"
   415 | "lb_arctan_horner prec (Suc n) k x =
   416     (lapprox_rat prec 1 k) - x * (ub_arctan_horner prec n (k + 2) x)"
   417 
   418 lemma arctan_0_1_bounds': assumes "0 \<le> real x" "real x \<le> 1" and "even n"
   419   shows "arctan x \<in> {(x * lb_arctan_horner prec n 1 (x * x)) .. (x * ub_arctan_horner prec (Suc n) 1 (x * x))}"
   420 proof -
   421   let "?c i" = "-1^i * (1 / (i * 2 + (1::nat)) * real x ^ (i * 2 + 1))"
   422   let "?S n" = "\<Sum> i=0..<n. ?c i"
   423 
   424   have "0 \<le> real (x * x)" by auto
   425   from `even n` obtain m where "2 * m = n" unfolding even_mult_two_ex by auto
   426 
   427   have "arctan x \<in> { ?S n .. ?S (Suc n) }"
   428   proof (cases "real x = 0")
   429     case False
   430     hence "0 < real x" using `0 \<le> real x` by auto
   431     hence prem: "0 < 1 / (0 * 2 + (1::nat)) * real x ^ (0 * 2 + 1)" by auto
   432 
   433     have "\<bar> real x \<bar> \<le> 1"  using `0 \<le> real x` `real x \<le> 1` by auto
   434     from mp[OF summable_Leibniz(2)[OF zeroseq_arctan_series[OF this] monoseq_arctan_series[OF this]] prem, THEN spec, of m, unfolded `2 * m = n`]
   435     show ?thesis unfolding arctan_series[OF `\<bar> real x \<bar> \<le> 1`] Suc_eq_plus1  .
   436   qed auto
   437   note arctan_bounds = this[unfolded atLeastAtMost_iff]
   438 
   439   have F: "\<And>n. 2 * Suc n + 1 = 2 * n + 1 + 2" by auto
   440 
   441   note bounds = horner_bounds[where s=1 and f="\<lambda>i. 2 * i + 1" and j'=0
   442     and lb="\<lambda>n i k x. lb_arctan_horner prec n k x"
   443     and ub="\<lambda>n i k x. ub_arctan_horner prec n k x",
   444     OF `0 \<le> real (x*x)` F lb_arctan_horner.simps ub_arctan_horner.simps]
   445 
   446   { have "(x * lb_arctan_horner prec n 1 (x*x)) \<le> ?S n"
   447       using bounds(1) `0 \<le> real x`
   448       unfolding real_of_float_mult power_add power_one_right mult_assoc[symmetric] setsum_left_distrib[symmetric]
   449       unfolding mult_commute[where 'a=real] mult_commute[of _ "2::nat"] power_mult power2_eq_square[of "real x"]
   450       by (auto intro!: mult_left_mono)
   451     also have "\<dots> \<le> arctan x" using arctan_bounds ..
   452     finally have "(x * lb_arctan_horner prec n 1 (x*x)) \<le> arctan x" . }
   453   moreover
   454   { have "arctan x \<le> ?S (Suc n)" using arctan_bounds ..
   455     also have "\<dots> \<le> (x * ub_arctan_horner prec (Suc n) 1 (x*x))"
   456       using bounds(2)[of "Suc n"] `0 \<le> real x`
   457       unfolding real_of_float_mult power_add power_one_right mult_assoc[symmetric] setsum_left_distrib[symmetric]
   458       unfolding mult_commute[where 'a=real] mult_commute[of _ "2::nat"] power_mult power2_eq_square[of "real x"]
   459       by (auto intro!: mult_left_mono)
   460     finally have "arctan x \<le> (x * ub_arctan_horner prec (Suc n) 1 (x*x))" . }
   461   ultimately show ?thesis by auto
   462 qed
   463 
   464 lemma arctan_0_1_bounds: assumes "0 \<le> real x" "real x \<le> 1"
   465   shows "arctan x \<in> {(x * lb_arctan_horner prec (get_even n) 1 (x * x)) .. (x * ub_arctan_horner prec (get_odd n) 1 (x * x))}"
   466 proof (cases "even n")
   467   case True
   468   obtain n' where "Suc n' = get_odd n" and "odd (Suc n')" using get_odd_ex by auto
   469   hence "even n'" unfolding even_Suc by auto
   470   have "arctan x \<le> x * ub_arctan_horner prec (get_odd n) 1 (x * x)"
   471     unfolding `Suc n' = get_odd n`[symmetric] using arctan_0_1_bounds'[OF `0 \<le> real x` `real x \<le> 1` `even n'`] by auto
   472   moreover
   473   have "x * lb_arctan_horner prec (get_even n) 1 (x * x) \<le> arctan x"
   474     unfolding get_even_def if_P[OF True] using arctan_0_1_bounds'[OF `0 \<le> real x` `real x \<le> 1` `even n`] by auto
   475   ultimately show ?thesis by auto
   476 next
   477   case False hence "0 < n" by (rule odd_pos)
   478   from gr0_implies_Suc[OF this] obtain n' where "n = Suc n'" ..
   479   from False[unfolded this even_Suc]
   480   have "even n'" and "even (Suc (Suc n'))" by auto
   481   have "get_odd n = Suc n'" unfolding get_odd_def if_P[OF False] using `n = Suc n'` .
   482 
   483   have "arctan x \<le> x * ub_arctan_horner prec (get_odd n) 1 (x * x)"
   484     unfolding `get_odd n = Suc n'` using arctan_0_1_bounds'[OF `0 \<le> real x` `real x \<le> 1` `even n'`] by auto
   485   moreover
   486   have "(x * lb_arctan_horner prec (get_even n) 1 (x * x)) \<le> arctan x"
   487     unfolding get_even_def if_not_P[OF False] unfolding `n = Suc n'` using arctan_0_1_bounds'[OF `0 \<le> real x` `real x \<le> 1` `even (Suc (Suc n'))`] by auto
   488   ultimately show ?thesis by auto
   489 qed
   490 
   491 subsection "Compute \<pi>"
   492 
   493 definition ub_pi :: "nat \<Rightarrow> float" where
   494   "ub_pi prec = (let A = rapprox_rat prec 1 5 ;
   495                      B = lapprox_rat prec 1 239
   496                  in ((Float 1 2) * ((Float 1 2) * A * (ub_arctan_horner prec (get_odd (prec div 4 + 1)) 1 (A * A)) -
   497                                                   B * (lb_arctan_horner prec (get_even (prec div 14 + 1)) 1 (B * B)))))"
   498 
   499 definition lb_pi :: "nat \<Rightarrow> float" where
   500   "lb_pi prec = (let A = lapprox_rat prec 1 5 ;
   501                      B = rapprox_rat prec 1 239
   502                  in ((Float 1 2) * ((Float 1 2) * A * (lb_arctan_horner prec (get_even (prec div 4 + 1)) 1 (A * A)) -
   503                                                   B * (ub_arctan_horner prec (get_odd (prec div 14 + 1)) 1 (B * B)))))"
   504 
   505 lemma pi_boundaries: "pi \<in> {(lb_pi n) .. (ub_pi n)}"
   506 proof -
   507   have machin_pi: "pi = 4 * (4 * arctan (1 / 5) - arctan (1 / 239))" unfolding machin[symmetric] by auto
   508 
   509   { fix prec n :: nat fix k :: int assume "1 < k" hence "0 \<le> k" and "0 < k" and "1 \<le> k" by auto
   510     let ?k = "rapprox_rat prec 1 k"
   511     have "1 div k = 0" using div_pos_pos_trivial[OF _ `1 < k`] by auto
   512 
   513     have "0 \<le> real ?k" by (rule order_trans[OF _ rapprox_rat], auto simp add: `0 \<le> k`)
   514     have "real ?k \<le> 1" unfolding rapprox_rat.simps(2)[OF zero_le_one `0 < k`]
   515       by (rule rapprox_posrat_le1, auto simp add: `0 < k` `1 \<le> k`)
   516 
   517     have "1 / k \<le> ?k" using rapprox_rat[where x=1 and y=k] by auto
   518     hence "arctan (1 / k) \<le> arctan ?k" by (rule arctan_monotone')
   519     also have "\<dots> \<le> (?k * ub_arctan_horner prec (get_odd n) 1 (?k * ?k))"
   520       using arctan_0_1_bounds[OF `0 \<le> real ?k` `real ?k \<le> 1`] by auto
   521     finally have "arctan (1 / k) \<le> ?k * ub_arctan_horner prec (get_odd n) 1 (?k * ?k)" .
   522   } note ub_arctan = this
   523 
   524   { fix prec n :: nat fix k :: int assume "1 < k" hence "0 \<le> k" and "0 < k" by auto
   525     let ?k = "lapprox_rat prec 1 k"
   526     have "1 div k = 0" using div_pos_pos_trivial[OF _ `1 < k`] by auto
   527     have "1 / k \<le> 1" using `1 < k` by auto
   528 
   529     have "\<And>n. 0 \<le> real ?k" using lapprox_rat_bottom[where x=1 and y=k, OF zero_le_one `0 < k`] by (auto simp add: `1 div k = 0`)
   530     have "\<And>n. real ?k \<le> 1" using lapprox_rat by (rule order_trans, auto simp add: `1 / k \<le> 1`)
   531 
   532     have "?k \<le> 1 / k" using lapprox_rat[where x=1 and y=k] by auto
   533 
   534     have "?k * lb_arctan_horner prec (get_even n) 1 (?k * ?k) \<le> arctan ?k"
   535       using arctan_0_1_bounds[OF `0 \<le> real ?k` `real ?k \<le> 1`] by auto
   536     also have "\<dots> \<le> arctan (1 / k)" using `?k \<le> 1 / k` by (rule arctan_monotone')
   537     finally have "?k * lb_arctan_horner prec (get_even n) 1 (?k * ?k) \<le> arctan (1 / k)" .
   538   } note lb_arctan = this
   539 
   540   have "pi \<le> ub_pi n"
   541     unfolding ub_pi_def machin_pi Let_def real_of_float_mult real_of_float_sub unfolding Float_num
   542     using lb_arctan[of 239] ub_arctan[of 5]
   543     by (auto intro!: mult_left_mono add_mono simp add: diff_minus simp del: lapprox_rat.simps rapprox_rat.simps)
   544   moreover
   545   have "lb_pi n \<le> pi"
   546     unfolding lb_pi_def machin_pi Let_def real_of_float_mult real_of_float_sub Float_num
   547     using lb_arctan[of 5] ub_arctan[of 239]
   548     by (auto intro!: mult_left_mono add_mono simp add: diff_minus simp del: lapprox_rat.simps rapprox_rat.simps)
   549   ultimately show ?thesis by auto
   550 qed
   551 
   552 subsection "Compute arcus tangens in the entire domain"
   553 
   554 function lb_arctan :: "nat \<Rightarrow> float \<Rightarrow> float" and ub_arctan :: "nat \<Rightarrow> float \<Rightarrow> float" where
   555   "lb_arctan prec x = (let ub_horner = \<lambda> x. x * ub_arctan_horner prec (get_odd (prec div 4 + 1)) 1 (x * x) ;
   556                            lb_horner = \<lambda> x. x * lb_arctan_horner prec (get_even (prec div 4 + 1)) 1 (x * x)
   557     in (if x < 0          then - ub_arctan prec (-x) else
   558         if x \<le> Float 1 -1 then lb_horner x else
   559         if x \<le> Float 1 1  then Float 1 1 * lb_horner (float_divl prec x (1 + ub_sqrt prec (1 + x * x)))
   560                           else (let inv = float_divr prec 1 x
   561                                 in if inv > 1 then 0
   562                                               else lb_pi prec * Float 1 -1 - ub_horner inv)))"
   563 
   564 | "ub_arctan prec x = (let lb_horner = \<lambda> x. x * lb_arctan_horner prec (get_even (prec div 4 + 1)) 1 (x * x) ;
   565                            ub_horner = \<lambda> x. x * ub_arctan_horner prec (get_odd (prec div 4 + 1)) 1 (x * x)
   566     in (if x < 0          then - lb_arctan prec (-x) else
   567         if x \<le> Float 1 -1 then ub_horner x else
   568         if x \<le> Float 1 1  then let y = float_divr prec x (1 + lb_sqrt prec (1 + x * x))
   569                                in if y > 1 then ub_pi prec * Float 1 -1
   570                                            else Float 1 1 * ub_horner y
   571                           else ub_pi prec * Float 1 -1 - lb_horner (float_divl prec 1 x)))"
   572 by pat_completeness auto
   573 termination by (relation "measure (\<lambda> v. let (prec, x) = sum_case id id v in (if x < 0 then 1 else 0))", auto simp add: less_float_def)
   574 
   575 declare ub_arctan_horner.simps[simp del]
   576 declare lb_arctan_horner.simps[simp del]
   577 
   578 lemma lb_arctan_bound': assumes "0 \<le> real x"
   579   shows "lb_arctan prec x \<le> arctan x"
   580 proof -
   581   have "\<not> x < 0" and "0 \<le> x" unfolding less_float_def le_float_def using `0 \<le> real x` by auto
   582   let "?ub_horner x" = "x * ub_arctan_horner prec (get_odd (prec div 4 + 1)) 1 (x * x)"
   583     and "?lb_horner x" = "x * lb_arctan_horner prec (get_even (prec div 4 + 1)) 1 (x * x)"
   584 
   585   show ?thesis
   586   proof (cases "x \<le> Float 1 -1")
   587     case True hence "real x \<le> 1" unfolding le_float_def Float_num by auto
   588     show ?thesis unfolding lb_arctan.simps Let_def if_not_P[OF `\<not> x < 0`] if_P[OF True]
   589       using arctan_0_1_bounds[OF `0 \<le> real x` `real x \<le> 1`] by auto
   590   next
   591     case False hence "0 < real x" unfolding le_float_def Float_num by auto
   592     let ?R = "1 + sqrt (1 + real x * real x)"
   593     let ?fR = "1 + ub_sqrt prec (1 + x * x)"
   594     let ?DIV = "float_divl prec x ?fR"
   595 
   596     have sqr_ge0: "0 \<le> 1 + real x * real x" using sum_power2_ge_zero[of 1 "real x", unfolded numeral_2_eq_2] by auto
   597     hence divisor_gt0: "0 < ?R" by (auto intro: add_pos_nonneg)
   598 
   599     have "sqrt (1 + x * x) \<le> ub_sqrt prec (1 + x * x)"
   600       using bnds_sqrt'[of "1 + x * x"] by auto
   601 
   602     hence "?R \<le> ?fR" by auto
   603     hence "0 < ?fR" and "0 < real ?fR" unfolding less_float_def using `0 < ?R` by auto
   604 
   605     have monotone: "(float_divl prec x ?fR) \<le> x / ?R"
   606     proof -
   607       have "?DIV \<le> real x / ?fR" by (rule float_divl)
   608       also have "\<dots> \<le> x / ?R" by (rule divide_left_mono[OF `?R \<le> ?fR` `0 \<le> real x` mult_pos_pos[OF order_less_le_trans[OF divisor_gt0 `?R \<le> real ?fR`] divisor_gt0]])
   609       finally show ?thesis .
   610     qed
   611 
   612     show ?thesis
   613     proof (cases "x \<le> Float 1 1")
   614       case True
   615 
   616       have "x \<le> sqrt (1 + x * x)" using real_sqrt_sum_squares_ge2[where x=1, unfolded numeral_2_eq_2] by auto
   617       also have "\<dots> \<le> (ub_sqrt prec (1 + x * x))"
   618         using bnds_sqrt'[of "1 + x * x"] by auto
   619       finally have "real x \<le> ?fR" by auto
   620       moreover have "?DIV \<le> real x / ?fR" by (rule float_divl)
   621       ultimately have "real ?DIV \<le> 1" unfolding divide_le_eq_1_pos[OF `0 < real ?fR`, symmetric] by auto
   622 
   623       have "0 \<le> real ?DIV" using float_divl_lower_bound[OF `0 \<le> x` `0 < ?fR`] unfolding le_float_def by auto
   624 
   625       have "(Float 1 1 * ?lb_horner ?DIV) \<le> 2 * arctan (float_divl prec x ?fR)" unfolding real_of_float_mult[of "Float 1 1"] Float_num
   626         using arctan_0_1_bounds[OF `0 \<le> real ?DIV` `real ?DIV \<le> 1`] by auto
   627       also have "\<dots> \<le> 2 * arctan (x / ?R)"
   628         using arctan_monotone'[OF monotone] by (auto intro!: mult_left_mono)
   629       also have "2 * arctan (x / ?R) = arctan x" using arctan_half[symmetric] unfolding numeral_2_eq_2 power_Suc2 power_0 mult_1_left .
   630       finally show ?thesis unfolding lb_arctan.simps Let_def if_not_P[OF `\<not> x < 0`] if_not_P[OF `\<not> x \<le> Float 1 -1`] if_P[OF True] .
   631     next
   632       case False
   633       hence "2 < real x" unfolding le_float_def Float_num by auto
   634       hence "1 \<le> real x" by auto
   635 
   636       let "?invx" = "float_divr prec 1 x"
   637       have "0 \<le> arctan x" using arctan_monotone'[OF `0 \<le> real x`] using arctan_tan[of 0, unfolded tan_zero] by auto
   638 
   639       show ?thesis
   640       proof (cases "1 < ?invx")
   641         case True
   642         show ?thesis unfolding lb_arctan.simps Let_def if_not_P[OF `\<not> x < 0`] if_not_P[OF `\<not> x \<le> Float 1 -1`] if_not_P[OF False] if_P[OF True]
   643           using `0 \<le> arctan x` by auto
   644       next
   645         case False
   646         hence "real ?invx \<le> 1" unfolding less_float_def by auto
   647         have "0 \<le> real ?invx" by (rule order_trans[OF _ float_divr], auto simp add: `0 \<le> real x`)
   648 
   649         have "1 / x \<noteq> 0" and "0 < 1 / x" using `0 < real x` by auto
   650 
   651         have "arctan (1 / x) \<le> arctan ?invx" unfolding real_of_float_1[symmetric] by (rule arctan_monotone', rule float_divr)
   652         also have "\<dots> \<le> (?ub_horner ?invx)" using arctan_0_1_bounds[OF `0 \<le> real ?invx` `real ?invx \<le> 1`] by auto
   653         finally have "pi / 2 - (?ub_horner ?invx) \<le> arctan x"
   654           using `0 \<le> arctan x` arctan_inverse[OF `1 / x \<noteq> 0`]
   655           unfolding real_sgn_pos[OF `0 < 1 / real x`] le_diff_eq by auto
   656         moreover
   657         have "lb_pi prec * Float 1 -1 \<le> pi / 2" unfolding real_of_float_mult Float_num times_divide_eq_right mult_1_left using pi_boundaries by auto
   658         ultimately
   659         show ?thesis unfolding lb_arctan.simps Let_def if_not_P[OF `\<not> x < 0`] if_not_P[OF `\<not> x \<le> Float 1 -1`] if_not_P[OF `\<not> x \<le> Float 1 1`] if_not_P[OF False]
   660           by auto
   661       qed
   662     qed
   663   qed
   664 qed
   665 
   666 lemma ub_arctan_bound': assumes "0 \<le> real x"
   667   shows "arctan x \<le> ub_arctan prec x"
   668 proof -
   669   have "\<not> x < 0" and "0 \<le> x" unfolding less_float_def le_float_def using `0 \<le> real x` by auto
   670 
   671   let "?ub_horner x" = "x * ub_arctan_horner prec (get_odd (prec div 4 + 1)) 1 (x * x)"
   672     and "?lb_horner x" = "x * lb_arctan_horner prec (get_even (prec div 4 + 1)) 1 (x * x)"
   673 
   674   show ?thesis
   675   proof (cases "x \<le> Float 1 -1")
   676     case True hence "real x \<le> 1" unfolding le_float_def Float_num by auto
   677     show ?thesis unfolding ub_arctan.simps Let_def if_not_P[OF `\<not> x < 0`] if_P[OF True]
   678       using arctan_0_1_bounds[OF `0 \<le> real x` `real x \<le> 1`] by auto
   679   next
   680     case False hence "0 < real x" unfolding le_float_def Float_num by auto
   681     let ?R = "1 + sqrt (1 + real x * real x)"
   682     let ?fR = "1 + lb_sqrt prec (1 + x * x)"
   683     let ?DIV = "float_divr prec x ?fR"
   684 
   685     have sqr_ge0: "0 \<le> 1 + real x * real x" using sum_power2_ge_zero[of 1 "real x", unfolded numeral_2_eq_2] by auto
   686     hence "0 \<le> real (1 + x*x)" by auto
   687 
   688     hence divisor_gt0: "0 < ?R" by (auto intro: add_pos_nonneg)
   689 
   690     have "lb_sqrt prec (1 + x * x) \<le> sqrt (1 + x * x)"
   691       using bnds_sqrt'[of "1 + x * x"] by auto
   692     hence "?fR \<le> ?R" by auto
   693     have "0 < real ?fR" unfolding real_of_float_add real_of_float_1 by (rule order_less_le_trans[OF zero_less_one], auto simp add: lb_sqrt_lower_bound[OF `0 \<le> real (1 + x*x)`])
   694 
   695     have monotone: "x / ?R \<le> (float_divr prec x ?fR)"
   696     proof -
   697       from divide_left_mono[OF `?fR \<le> ?R` `0 \<le> real x` mult_pos_pos[OF divisor_gt0 `0 < real ?fR`]]
   698       have "x / ?R \<le> x / ?fR" .
   699       also have "\<dots> \<le> ?DIV" by (rule float_divr)
   700       finally show ?thesis .
   701     qed
   702 
   703     show ?thesis
   704     proof (cases "x \<le> Float 1 1")
   705       case True
   706       show ?thesis
   707       proof (cases "?DIV > 1")
   708         case True
   709         have "pi / 2 \<le> ub_pi prec * Float 1 -1" unfolding real_of_float_mult Float_num times_divide_eq_right mult_1_left using pi_boundaries by auto
   710         from order_less_le_trans[OF arctan_ubound this, THEN less_imp_le]
   711         show ?thesis unfolding ub_arctan.simps Let_def if_not_P[OF `\<not> x < 0`] if_not_P[OF `\<not> x \<le> Float 1 -1`] if_P[OF `x \<le> Float 1 1`] if_P[OF True] .
   712       next
   713         case False
   714         hence "real ?DIV \<le> 1" unfolding less_float_def by auto
   715 
   716         have "0 \<le> x / ?R" using `0 \<le> real x` `0 < ?R` unfolding real_0_le_divide_iff by auto
   717         hence "0 \<le> real ?DIV" using monotone by (rule order_trans)
   718 
   719         have "arctan x = 2 * arctan (x / ?R)" using arctan_half unfolding numeral_2_eq_2 power_Suc2 power_0 mult_1_left .
   720         also have "\<dots> \<le> 2 * arctan (?DIV)"
   721           using arctan_monotone'[OF monotone] by (auto intro!: mult_left_mono)
   722         also have "\<dots> \<le> (Float 1 1 * ?ub_horner ?DIV)" unfolding real_of_float_mult[of "Float 1 1"] Float_num
   723           using arctan_0_1_bounds[OF `0 \<le> real ?DIV` `real ?DIV \<le> 1`] by auto
   724         finally show ?thesis unfolding ub_arctan.simps Let_def if_not_P[OF `\<not> x < 0`] if_not_P[OF `\<not> x \<le> Float 1 -1`] if_P[OF `x \<le> Float 1 1`] if_not_P[OF False] .
   725       qed
   726     next
   727       case False
   728       hence "2 < real x" unfolding le_float_def Float_num by auto
   729       hence "1 \<le> real x" by auto
   730       hence "0 < real x" by auto
   731       hence "0 < x" unfolding less_float_def by auto
   732 
   733       let "?invx" = "float_divl prec 1 x"
   734       have "0 \<le> arctan x" using arctan_monotone'[OF `0 \<le> real x`] using arctan_tan[of 0, unfolded tan_zero] by auto
   735 
   736       have "real ?invx \<le> 1" unfolding less_float_def by (rule order_trans[OF float_divl], auto simp add: `1 \<le> real x` divide_le_eq_1_pos[OF `0 < real x`])
   737       have "0 \<le> real ?invx" unfolding real_of_float_0[symmetric] by (rule float_divl_lower_bound[unfolded le_float_def], auto simp add: `0 < x`)
   738 
   739       have "1 / x \<noteq> 0" and "0 < 1 / x" using `0 < real x` by auto
   740 
   741       have "(?lb_horner ?invx) \<le> arctan (?invx)" using arctan_0_1_bounds[OF `0 \<le> real ?invx` `real ?invx \<le> 1`] by auto
   742       also have "\<dots> \<le> arctan (1 / x)" unfolding real_of_float_1[symmetric] by (rule arctan_monotone', rule float_divl)
   743       finally have "arctan x \<le> pi / 2 - (?lb_horner ?invx)"
   744         using `0 \<le> arctan x` arctan_inverse[OF `1 / x \<noteq> 0`]
   745         unfolding real_sgn_pos[OF `0 < 1 / x`] le_diff_eq by auto
   746       moreover
   747       have "pi / 2 \<le> ub_pi prec * Float 1 -1" unfolding real_of_float_mult Float_num times_divide_eq_right mult_1_right using pi_boundaries by auto
   748       ultimately
   749       show ?thesis unfolding ub_arctan.simps Let_def if_not_P[OF `\<not> x < 0`] if_not_P[OF `\<not> x \<le> Float 1 -1`] if_not_P[OF `\<not> x \<le> Float 1 1`] if_not_P[OF False]
   750         by auto
   751     qed
   752   qed
   753 qed
   754 
   755 lemma arctan_boundaries:
   756   "arctan x \<in> {(lb_arctan prec x) .. (ub_arctan prec x)}"
   757 proof (cases "0 \<le> x")
   758   case True hence "0 \<le> real x" unfolding le_float_def by auto
   759   show ?thesis using ub_arctan_bound'[OF `0 \<le> real x`] lb_arctan_bound'[OF `0 \<le> real x`] unfolding atLeastAtMost_iff by auto
   760 next
   761   let ?mx = "-x"
   762   case False hence "x < 0" and "0 \<le> real ?mx" unfolding le_float_def less_float_def by auto
   763   hence bounds: "lb_arctan prec ?mx \<le> arctan ?mx \<and> arctan ?mx \<le> ub_arctan prec ?mx"
   764     using ub_arctan_bound'[OF `0 \<le> real ?mx`] lb_arctan_bound'[OF `0 \<le> real ?mx`] by auto
   765   show ?thesis unfolding real_of_float_minus arctan_minus lb_arctan.simps[where x=x] ub_arctan.simps[where x=x] Let_def if_P[OF `x < 0`]
   766     unfolding atLeastAtMost_iff using bounds[unfolded real_of_float_minus arctan_minus] by auto
   767 qed
   768 
   769 lemma bnds_arctan: "\<forall> (x::real) lx ux. (l, u) = (lb_arctan prec lx, ub_arctan prec ux) \<and> x \<in> {lx .. ux} \<longrightarrow> l \<le> arctan x \<and> arctan x \<le> u"
   770 proof (rule allI, rule allI, rule allI, rule impI)
   771   fix x :: real fix lx ux
   772   assume "(l, u) = (lb_arctan prec lx, ub_arctan prec ux) \<and> x \<in> {lx .. ux}"
   773   hence l: "lb_arctan prec lx = l " and u: "ub_arctan prec ux = u" and x: "x \<in> {lx .. ux}" by auto
   774 
   775   { from arctan_boundaries[of lx prec, unfolded l]
   776     have "l \<le> arctan lx" by (auto simp del: lb_arctan.simps)
   777     also have "\<dots> \<le> arctan x" using x by (auto intro: arctan_monotone')
   778     finally have "l \<le> arctan x" .
   779   } moreover
   780   { have "arctan x \<le> arctan ux" using x by (auto intro: arctan_monotone')
   781     also have "\<dots> \<le> u" using arctan_boundaries[of ux prec, unfolded u] by (auto simp del: ub_arctan.simps)
   782     finally have "arctan x \<le> u" .
   783   } ultimately show "l \<le> arctan x \<and> arctan x \<le> u" ..
   784 qed
   785 
   786 section "Sinus and Cosinus"
   787 
   788 subsection "Compute the cosinus and sinus series"
   789 
   790 fun ub_sin_cos_aux :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> float \<Rightarrow> float"
   791 and lb_sin_cos_aux :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> float \<Rightarrow> float" where
   792   "ub_sin_cos_aux prec 0 i k x = 0"
   793 | "ub_sin_cos_aux prec (Suc n) i k x =
   794     (rapprox_rat prec 1 k) - x * (lb_sin_cos_aux prec n (i + 2) (k * i * (i + 1)) x)"
   795 | "lb_sin_cos_aux prec 0 i k x = 0"
   796 | "lb_sin_cos_aux prec (Suc n) i k x =
   797     (lapprox_rat prec 1 k) - x * (ub_sin_cos_aux prec n (i + 2) (k * i * (i + 1)) x)"
   798 lemma cos_aux:
   799   shows "(lb_sin_cos_aux prec n 1 1 (x * x)) \<le> (\<Sum> i=0..<n. -1^i * (1/real (fact (2 * i))) * x ^(2 * i))" (is "?lb")
   800   and "(\<Sum> i=0..<n. -1^i * (1/real (fact (2 * i))) * x^(2 * i)) \<le> (ub_sin_cos_aux prec n 1 1 (x * x))" (is "?ub")
   801 proof -
   802   have "0 \<le> real (x * x)" unfolding real_of_float_mult by auto
   803   let "?f n" = "fact (2 * n)"
   804 
   805   { fix n
   806     have F: "\<And>m. ((\<lambda>i. i + 2) ^^ n) m = m + 2 * n" by (induct n arbitrary: m, auto)
   807     have "?f (Suc n) = ?f n * ((\<lambda>i. i + 2) ^^ n) 1 * (((\<lambda>i. i + 2) ^^ n) 1 + 1)"
   808       unfolding F by auto } note f_eq = this
   809 
   810   from horner_bounds[where lb="lb_sin_cos_aux prec" and ub="ub_sin_cos_aux prec" and j'=0,
   811     OF `0 \<le> real (x * x)` f_eq lb_sin_cos_aux.simps ub_sin_cos_aux.simps]
   812   show "?lb" and "?ub" by (auto simp add: power_mult power2_eq_square[of "real x"])
   813 qed
   814 
   815 lemma cos_boundaries: assumes "0 \<le> real x" and "x \<le> pi / 2"
   816   shows "cos x \<in> {(lb_sin_cos_aux prec (get_even n) 1 1 (x * x)) .. (ub_sin_cos_aux prec (get_odd n) 1 1 (x * x))}"
   817 proof (cases "real x = 0")
   818   case False hence "real x \<noteq> 0" by auto
   819   hence "0 < x" and "0 < real x" using `0 \<le> real x` unfolding less_float_def by auto
   820   have "0 < x * x" using `0 < x` unfolding less_float_def real_of_float_mult real_of_float_0
   821     using mult_pos_pos[where a="real x" and b="real x"] by auto
   822 
   823   { fix x n have "(\<Sum> i=0..<n. -1^i * (1/real (fact (2 * i))) * x ^ (2 * i))
   824     = (\<Sum> i = 0 ..< 2 * n. (if even(i) then (-1 ^ (i div 2))/(real (fact i)) else 0) * x ^ i)" (is "?sum = ?ifsum")
   825   proof -
   826     have "?sum = ?sum + (\<Sum> j = 0 ..< n. 0)" by auto
   827     also have "\<dots> =
   828       (\<Sum> j = 0 ..< n. -1 ^ ((2 * j) div 2) / (real (fact (2 * j))) * x ^(2 * j)) + (\<Sum> j = 0 ..< n. 0)" by auto
   829     also have "\<dots> = (\<Sum> i = 0 ..< 2 * n. if even i then -1 ^ (i div 2) / (real (fact i)) * x ^ i else 0)"
   830       unfolding sum_split_even_odd ..
   831     also have "\<dots> = (\<Sum> i = 0 ..< 2 * n. (if even i then -1 ^ (i div 2) / (real (fact i)) else 0) * x ^ i)"
   832       by (rule setsum_cong2) auto
   833     finally show ?thesis by assumption
   834   qed } note morph_to_if_power = this
   835 
   836 
   837   { fix n :: nat assume "0 < n"
   838     hence "0 < 2 * n" by auto
   839     obtain t where "0 < t" and "t < real x" and
   840       cos_eq: "cos x = (\<Sum> i = 0 ..< 2 * n. (if even(i) then (-1 ^ (i div 2))/(real (fact i)) else 0) * (real x) ^ i)
   841       + (cos (t + 1/2 * (2 * n) * pi) / real (fact (2*n))) * (real x)^(2*n)"
   842       (is "_ = ?SUM + ?rest / ?fact * ?pow")
   843       using Maclaurin_cos_expansion2[OF `0 < real x` `0 < 2 * n`] by auto
   844 
   845     have "cos t * -1^n = cos t * cos (n * pi) + sin t * sin (n * pi)" by auto
   846     also have "\<dots> = cos (t + n * pi)"  using cos_add by auto
   847     also have "\<dots> = ?rest" by auto
   848     finally have "cos t * -1^n = ?rest" .
   849     moreover
   850     have "t \<le> pi / 2" using `t < real x` and `x \<le> pi / 2` by auto
   851     hence "0 \<le> cos t" using `0 < t` and cos_ge_zero by auto
   852     ultimately have even: "even n \<Longrightarrow> 0 \<le> ?rest" and odd: "odd n \<Longrightarrow> 0 \<le> - ?rest " by auto
   853 
   854     have "0 < ?fact" by auto
   855     have "0 < ?pow" using `0 < real x` by auto
   856 
   857     {
   858       assume "even n"
   859       have "(lb_sin_cos_aux prec n 1 1 (x * x)) \<le> ?SUM"
   860         unfolding morph_to_if_power[symmetric] using cos_aux by auto
   861       also have "\<dots> \<le> cos x"
   862       proof -
   863         from even[OF `even n`] `0 < ?fact` `0 < ?pow`
   864         have "0 \<le> (?rest / ?fact) * ?pow" by (metis mult_nonneg_nonneg divide_nonneg_pos less_imp_le)
   865         thus ?thesis unfolding cos_eq by auto
   866       qed
   867       finally have "(lb_sin_cos_aux prec n 1 1 (x * x)) \<le> cos x" .
   868     } note lb = this
   869 
   870     {
   871       assume "odd n"
   872       have "cos x \<le> ?SUM"
   873       proof -
   874         from `0 < ?fact` and `0 < ?pow` and odd[OF `odd n`]
   875         have "0 \<le> (- ?rest) / ?fact * ?pow"
   876           by (metis mult_nonneg_nonneg divide_nonneg_pos less_imp_le)
   877         thus ?thesis unfolding cos_eq by auto
   878       qed
   879       also have "\<dots> \<le> (ub_sin_cos_aux prec n 1 1 (x * x))"
   880         unfolding morph_to_if_power[symmetric] using cos_aux by auto
   881       finally have "cos x \<le> (ub_sin_cos_aux prec n 1 1 (x * x))" .
   882     } note ub = this and lb
   883   } note ub = this(1) and lb = this(2)
   884 
   885   have "cos x \<le> (ub_sin_cos_aux prec (get_odd n) 1 1 (x * x))" using ub[OF odd_pos[OF get_odd] get_odd] .
   886   moreover have "(lb_sin_cos_aux prec (get_even n) 1 1 (x * x)) \<le> cos x"
   887   proof (cases "0 < get_even n")
   888     case True show ?thesis using lb[OF True get_even] .
   889   next
   890     case False
   891     hence "get_even n = 0" by auto
   892     have "- (pi / 2) \<le> x" by (rule order_trans[OF _ `0 < real x`[THEN less_imp_le]], auto)
   893     with `x \<le> pi / 2`
   894     show ?thesis unfolding `get_even n = 0` lb_sin_cos_aux.simps real_of_float_minus real_of_float_0 using cos_ge_zero by auto
   895   qed
   896   ultimately show ?thesis by auto
   897 next
   898   case True
   899   show ?thesis
   900   proof (cases "n = 0")
   901     case True
   902     thus ?thesis unfolding `n = 0` get_even_def get_odd_def using `real x = 0` lapprox_rat[where x="-1" and y=1] by auto
   903   next
   904     case False with not0_implies_Suc obtain m where "n = Suc m" by blast
   905     thus ?thesis unfolding `n = Suc m` get_even_def get_odd_def using `real x = 0` rapprox_rat[where x=1 and y=1] lapprox_rat[where x=1 and y=1] by (cases "even (Suc m)", auto)
   906   qed
   907 qed
   908 
   909 lemma sin_aux: assumes "0 \<le> real x"
   910   shows "(x * lb_sin_cos_aux prec n 2 1 (x * x)) \<le> (\<Sum> i=0..<n. -1^i * (1/real (fact (2 * i + 1))) * x^(2 * i + 1))" (is "?lb")
   911   and "(\<Sum> i=0..<n. -1^i * (1/real (fact (2 * i + 1))) * x^(2 * i + 1)) \<le> (x * ub_sin_cos_aux prec n 2 1 (x * x))" (is "?ub")
   912 proof -
   913   have "0 \<le> real (x * x)" unfolding real_of_float_mult by auto
   914   let "?f n" = "fact (2 * n + 1)"
   915 
   916   { fix n
   917     have F: "\<And>m. ((\<lambda>i. i + 2) ^^ n) m = m + 2 * n" by (induct n arbitrary: m, auto)
   918     have "?f (Suc n) = ?f n * ((\<lambda>i. i + 2) ^^ n) 2 * (((\<lambda>i. i + 2) ^^ n) 2 + 1)"
   919       unfolding F by auto } note f_eq = this
   920 
   921   from horner_bounds[where lb="lb_sin_cos_aux prec" and ub="ub_sin_cos_aux prec" and j'=0,
   922     OF `0 \<le> real (x * x)` f_eq lb_sin_cos_aux.simps ub_sin_cos_aux.simps]
   923   show "?lb" and "?ub" using `0 \<le> real x` unfolding real_of_float_mult
   924     unfolding power_add power_one_right mult_assoc[symmetric] setsum_left_distrib[symmetric]
   925     unfolding mult_commute[where 'a=real]
   926     by (auto intro!: mult_left_mono simp add: power_mult power2_eq_square[of "real x"])
   927 qed
   928 
   929 lemma sin_boundaries: assumes "0 \<le> real x" and "x \<le> pi / 2"
   930   shows "sin x \<in> {(x * lb_sin_cos_aux prec (get_even n) 2 1 (x * x)) .. (x * ub_sin_cos_aux prec (get_odd n) 2 1 (x * x))}"
   931 proof (cases "real x = 0")
   932   case False hence "real x \<noteq> 0" by auto
   933   hence "0 < x" and "0 < real x" using `0 \<le> real x` unfolding less_float_def by auto
   934   have "0 < x * x" using `0 < x` unfolding less_float_def real_of_float_mult real_of_float_0
   935     using mult_pos_pos[where a="real x" and b="real x"] by auto
   936 
   937   { fix x n have "(\<Sum> j = 0 ..< n. -1 ^ (((2 * j + 1) - Suc 0) div 2) / (real (fact (2 * j + 1))) * x ^(2 * j + 1))
   938     = (\<Sum> i = 0 ..< 2 * n. (if even(i) then 0 else (-1 ^ ((i - Suc 0) div 2))/(real (fact i))) * x ^ i)" (is "?SUM = _")
   939     proof -
   940       have pow: "!!i. x ^ (2 * i + 1) = x * x ^ (2 * i)" by auto
   941       have "?SUM = (\<Sum> j = 0 ..< n. 0) + ?SUM" by auto
   942       also have "\<dots> = (\<Sum> i = 0 ..< 2 * n. if even i then 0 else -1 ^ ((i - Suc 0) div 2) / (real (fact i)) * x ^ i)"
   943         unfolding sum_split_even_odd ..
   944       also have "\<dots> = (\<Sum> i = 0 ..< 2 * n. (if even i then 0 else -1 ^ ((i - Suc 0) div 2) / (real (fact i))) * x ^ i)"
   945         by (rule setsum_cong2) auto
   946       finally show ?thesis by assumption
   947     qed } note setsum_morph = this
   948 
   949   { fix n :: nat assume "0 < n"
   950     hence "0 < 2 * n + 1" by auto
   951     obtain t where "0 < t" and "t < real x" and
   952       sin_eq: "sin x = (\<Sum> i = 0 ..< 2 * n + 1. (if even(i) then 0 else (-1 ^ ((i - Suc 0) div 2))/(real (fact i))) * (real x) ^ i)
   953       + (sin (t + 1/2 * (2 * n + 1) * pi) / real (fact (2*n + 1))) * (real x)^(2*n + 1)"
   954       (is "_ = ?SUM + ?rest / ?fact * ?pow")
   955       using Maclaurin_sin_expansion3[OF `0 < 2 * n + 1` `0 < real x`] by auto
   956 
   957     have "?rest = cos t * -1^n" unfolding sin_add cos_add real_of_nat_add left_distrib right_distrib by auto
   958     moreover
   959     have "t \<le> pi / 2" using `t < real x` and `x \<le> pi / 2` by auto
   960     hence "0 \<le> cos t" using `0 < t` and cos_ge_zero by auto
   961     ultimately have even: "even n \<Longrightarrow> 0 \<le> ?rest" and odd: "odd n \<Longrightarrow> 0 \<le> - ?rest " by auto
   962 
   963     have "0 < ?fact" by (rule real_of_nat_fact_gt_zero)
   964     have "0 < ?pow" using `0 < real x` by (rule zero_less_power)
   965 
   966     {
   967       assume "even n"
   968       have "(x * lb_sin_cos_aux prec n 2 1 (x * x)) \<le>
   969             (\<Sum> i = 0 ..< 2 * n. (if even(i) then 0 else (-1 ^ ((i - Suc 0) div 2))/(real (fact i))) * (real x) ^ i)"
   970         using sin_aux[OF `0 \<le> real x`] unfolding setsum_morph[symmetric] by auto
   971       also have "\<dots> \<le> ?SUM" by auto
   972       also have "\<dots> \<le> sin x"
   973       proof -
   974         from even[OF `even n`] `0 < ?fact` `0 < ?pow`
   975         have "0 \<le> (?rest / ?fact) * ?pow" by (metis mult_nonneg_nonneg divide_nonneg_pos less_imp_le)
   976         thus ?thesis unfolding sin_eq by auto
   977       qed
   978       finally have "(x * lb_sin_cos_aux prec n 2 1 (x * x)) \<le> sin x" .
   979     } note lb = this
   980 
   981     {
   982       assume "odd n"
   983       have "sin x \<le> ?SUM"
   984       proof -
   985         from `0 < ?fact` and `0 < ?pow` and odd[OF `odd n`]
   986         have "0 \<le> (- ?rest) / ?fact * ?pow"
   987           by (metis mult_nonneg_nonneg divide_nonneg_pos less_imp_le)
   988         thus ?thesis unfolding sin_eq by auto
   989       qed
   990       also have "\<dots> \<le> (\<Sum> i = 0 ..< 2 * n. (if even(i) then 0 else (-1 ^ ((i - Suc 0) div 2))/(real (fact i))) * (real x) ^ i)"
   991          by auto
   992       also have "\<dots> \<le> (x * ub_sin_cos_aux prec n 2 1 (x * x))"
   993         using sin_aux[OF `0 \<le> real x`] unfolding setsum_morph[symmetric] by auto
   994       finally have "sin x \<le> (x * ub_sin_cos_aux prec n 2 1 (x * x))" .
   995     } note ub = this and lb
   996   } note ub = this(1) and lb = this(2)
   997 
   998   have "sin x \<le> (x * ub_sin_cos_aux prec (get_odd n) 2 1 (x * x))" using ub[OF odd_pos[OF get_odd] get_odd] .
   999   moreover have "(x * lb_sin_cos_aux prec (get_even n) 2 1 (x * x)) \<le> sin x"
  1000   proof (cases "0 < get_even n")
  1001     case True show ?thesis using lb[OF True get_even] .
  1002   next
  1003     case False
  1004     hence "get_even n = 0" by auto
  1005     with `x \<le> pi / 2` `0 \<le> real x`
  1006     show ?thesis unfolding `get_even n = 0` ub_sin_cos_aux.simps real_of_float_minus real_of_float_0 using sin_ge_zero by auto
  1007   qed
  1008   ultimately show ?thesis by auto
  1009 next
  1010   case True
  1011   show ?thesis
  1012   proof (cases "n = 0")
  1013     case True
  1014     thus ?thesis unfolding `n = 0` get_even_def get_odd_def using `real x = 0` lapprox_rat[where x="-1" and y=1] by auto
  1015   next
  1016     case False with not0_implies_Suc obtain m where "n = Suc m" by blast
  1017     thus ?thesis unfolding `n = Suc m` get_even_def get_odd_def using `real x = 0` rapprox_rat[where x=1 and y=1] lapprox_rat[where x=1 and y=1] by (cases "even (Suc m)", auto)
  1018   qed
  1019 qed
  1020 
  1021 subsection "Compute the cosinus in the entire domain"
  1022 
  1023 definition lb_cos :: "nat \<Rightarrow> float \<Rightarrow> float" where
  1024 "lb_cos prec x = (let
  1025     horner = \<lambda> x. lb_sin_cos_aux prec (get_even (prec div 4 + 1)) 1 1 (x * x) ;
  1026     half = \<lambda> x. if x < 0 then - 1 else Float 1 1 * x * x - 1
  1027   in if x < Float 1 -1 then horner x
  1028 else if x < 1          then half (horner (x * Float 1 -1))
  1029                        else half (half (horner (x * Float 1 -2))))"
  1030 
  1031 definition ub_cos :: "nat \<Rightarrow> float \<Rightarrow> float" where
  1032 "ub_cos prec x = (let
  1033     horner = \<lambda> x. ub_sin_cos_aux prec (get_odd (prec div 4 + 1)) 1 1 (x * x) ;
  1034     half = \<lambda> x. Float 1 1 * x * x - 1
  1035   in if x < Float 1 -1 then horner x
  1036 else if x < 1          then half (horner (x * Float 1 -1))
  1037                        else half (half (horner (x * Float 1 -2))))"
  1038 
  1039 lemma lb_cos: assumes "0 \<le> real x" and "x \<le> pi"
  1040   shows "cos x \<in> {(lb_cos prec x) .. (ub_cos prec x)}" (is "?cos x \<in> {(?lb x) .. (?ub x) }")
  1041 proof -
  1042   { fix x :: real
  1043     have "cos x = cos (x / 2 + x / 2)" by auto
  1044     also have "\<dots> = cos (x / 2) * cos (x / 2) + sin (x / 2) * sin (x / 2) - sin (x / 2) * sin (x / 2) + cos (x / 2) * cos (x / 2) - 1"
  1045       unfolding cos_add by auto
  1046     also have "\<dots> = 2 * cos (x / 2) * cos (x / 2) - 1" by algebra
  1047     finally have "cos x = 2 * cos (x / 2) * cos (x / 2) - 1" .
  1048   } note x_half = this[symmetric]
  1049 
  1050   have "\<not> x < 0" using `0 \<le> real x` unfolding less_float_def by auto
  1051   let "?ub_horner x" = "ub_sin_cos_aux prec (get_odd (prec div 4 + 1)) 1 1 (x * x)"
  1052   let "?lb_horner x" = "lb_sin_cos_aux prec (get_even (prec div 4 + 1)) 1 1 (x * x)"
  1053   let "?ub_half x" = "Float 1 1 * x * x - 1"
  1054   let "?lb_half x" = "if x < 0 then - 1 else Float 1 1 * x * x - 1"
  1055 
  1056   show ?thesis
  1057   proof (cases "x < Float 1 -1")
  1058     case True hence "x \<le> pi / 2" unfolding less_float_def using pi_ge_two by auto
  1059     show ?thesis unfolding lb_cos_def[where x=x] ub_cos_def[where x=x] if_not_P[OF `\<not> x < 0`] if_P[OF `x < Float 1 -1`] Let_def
  1060       using cos_boundaries[OF `0 \<le> real x` `x \<le> pi / 2`] .
  1061   next
  1062     case False
  1063     { fix y x :: float let ?x2 = "(x * Float 1 -1)"
  1064       assume "y \<le> cos ?x2" and "-pi \<le> x" and "x \<le> pi"
  1065       hence "- (pi / 2) \<le> ?x2" and "?x2 \<le> pi / 2" using pi_ge_two unfolding real_of_float_mult Float_num by auto
  1066       hence "0 \<le> cos ?x2" by (rule cos_ge_zero)
  1067 
  1068       have "(?lb_half y) \<le> cos x"
  1069       proof (cases "y < 0")
  1070         case True show ?thesis using cos_ge_minus_one unfolding if_P[OF True] by auto
  1071       next
  1072         case False
  1073         hence "0 \<le> real y" unfolding less_float_def by auto
  1074         from mult_mono[OF `y \<le> cos ?x2` `y \<le> cos ?x2` `0 \<le> cos ?x2` this]
  1075         have "real y * real y \<le> cos ?x2 * cos ?x2" .
  1076         hence "2 * real y * real y \<le> 2 * cos ?x2 * cos ?x2" by auto
  1077         hence "2 * real y * real y - 1 \<le> 2 * cos (x / 2) * cos (x / 2) - 1" unfolding Float_num real_of_float_mult by auto
  1078         thus ?thesis unfolding if_not_P[OF False] x_half Float_num real_of_float_mult real_of_float_sub by auto
  1079       qed
  1080     } note lb_half = this
  1081 
  1082     { fix y x :: float let ?x2 = "(x * Float 1 -1)"
  1083       assume ub: "cos ?x2 \<le> y" and "- pi \<le> x" and "x \<le> pi"
  1084       hence "- (pi / 2) \<le> ?x2" and "?x2 \<le> pi / 2" using pi_ge_two unfolding real_of_float_mult Float_num by auto
  1085       hence "0 \<le> cos ?x2" by (rule cos_ge_zero)
  1086 
  1087       have "cos x \<le> (?ub_half y)"
  1088       proof -
  1089         have "0 \<le> real y" using `0 \<le> cos ?x2` ub by (rule order_trans)
  1090         from mult_mono[OF ub ub this `0 \<le> cos ?x2`]
  1091         have "cos ?x2 * cos ?x2 \<le> real y * real y" .
  1092         hence "2 * cos ?x2 * cos ?x2 \<le> 2 * real y * real y" by auto
  1093         hence "2 * cos (x / 2) * cos (x / 2) - 1 \<le> 2 * real y * real y - 1" unfolding Float_num real_of_float_mult by auto
  1094         thus ?thesis unfolding x_half real_of_float_mult Float_num real_of_float_sub by auto
  1095       qed
  1096     } note ub_half = this
  1097 
  1098     let ?x2 = "x * Float 1 -1"
  1099     let ?x4 = "x * Float 1 -1 * Float 1 -1"
  1100 
  1101     have "-pi \<le> x" using pi_ge_zero[THEN le_imp_neg_le, unfolded minus_zero] `0 \<le> real x` by (rule order_trans)
  1102 
  1103     show ?thesis
  1104     proof (cases "x < 1")
  1105       case True hence "real x \<le> 1" unfolding less_float_def by auto
  1106       have "0 \<le> real ?x2" and "?x2 \<le> pi / 2" using pi_ge_two `0 \<le> real x` unfolding real_of_float_mult Float_num using assms by auto
  1107       from cos_boundaries[OF this]
  1108       have lb: "(?lb_horner ?x2) \<le> ?cos ?x2" and ub: "?cos ?x2 \<le> (?ub_horner ?x2)" by auto
  1109 
  1110       have "(?lb x) \<le> ?cos x"
  1111       proof -
  1112         from lb_half[OF lb `-pi \<le> x` `x \<le> pi`]
  1113         show ?thesis unfolding lb_cos_def[where x=x] Let_def using `\<not> x < 0` `\<not> x < Float 1 -1` `x < 1` by auto
  1114       qed
  1115       moreover have "?cos x \<le> (?ub x)"
  1116       proof -
  1117         from ub_half[OF ub `-pi \<le> x` `x \<le> pi`]
  1118         show ?thesis unfolding ub_cos_def[where x=x] Let_def using `\<not> x < 0` `\<not> x < Float 1 -1` `x < 1` by auto
  1119       qed
  1120       ultimately show ?thesis by auto
  1121     next
  1122       case False
  1123       have "0 \<le> real ?x4" and "?x4 \<le> pi / 2" using pi_ge_two `0 \<le> real x` `x \<le> pi` unfolding real_of_float_mult Float_num by auto
  1124       from cos_boundaries[OF this]
  1125       have lb: "(?lb_horner ?x4) \<le> ?cos ?x4" and ub: "?cos ?x4 \<le> (?ub_horner ?x4)" by auto
  1126 
  1127       have eq_4: "?x2 * Float 1 -1 = x * Float 1 -2" by (cases x, auto simp add: times_float.simps)
  1128 
  1129       have "(?lb x) \<le> ?cos x"
  1130       proof -
  1131         have "-pi \<le> ?x2" and "?x2 \<le> pi" unfolding real_of_float_mult Float_num using pi_ge_two `0 \<le> real x` `x \<le> pi` by auto
  1132         from lb_half[OF lb_half[OF lb this] `-pi \<le> x` `x \<le> pi`, unfolded eq_4]
  1133         show ?thesis unfolding lb_cos_def[where x=x] if_not_P[OF `\<not> x < 0`] if_not_P[OF `\<not> x < Float 1 -1`] if_not_P[OF `\<not> x < 1`] Let_def .
  1134       qed
  1135       moreover have "?cos x \<le> (?ub x)"
  1136       proof -
  1137         have "-pi \<le> ?x2" and "?x2 \<le> pi" unfolding real_of_float_mult Float_num using pi_ge_two `0 \<le> real x` ` x \<le> pi` by auto
  1138         from ub_half[OF ub_half[OF ub this] `-pi \<le> x` `x \<le> pi`, unfolded eq_4]
  1139         show ?thesis unfolding ub_cos_def[where x=x] if_not_P[OF `\<not> x < 0`] if_not_P[OF `\<not> x < Float 1 -1`] if_not_P[OF `\<not> x < 1`] Let_def .
  1140       qed
  1141       ultimately show ?thesis by auto
  1142     qed
  1143   qed
  1144 qed
  1145 
  1146 lemma lb_cos_minus: assumes "-pi \<le> x" and "real x \<le> 0"
  1147   shows "cos (real(-x)) \<in> {(lb_cos prec (-x)) .. (ub_cos prec (-x))}"
  1148 proof -
  1149   have "0 \<le> real (-x)" and "(-x) \<le> pi" using `-pi \<le> x` `real x \<le> 0` by auto
  1150   from lb_cos[OF this] show ?thesis .
  1151 qed
  1152 
  1153 definition bnds_cos :: "nat \<Rightarrow> float \<Rightarrow> float \<Rightarrow> float * float" where
  1154 "bnds_cos prec lx ux = (let
  1155     lpi = round_down prec (lb_pi prec) ;
  1156     upi = round_up prec (ub_pi prec) ;
  1157     k = floor_fl (float_divr prec (lx + lpi) (2 * lpi)) ;
  1158     lx = lx - k * 2 * (if k < 0 then lpi else upi) ;
  1159     ux = ux - k * 2 * (if k < 0 then upi else lpi)
  1160   in   if - lpi \<le> lx \<and> ux \<le> 0    then (lb_cos prec (-lx), ub_cos prec (-ux))
  1161   else if 0 \<le> lx \<and> ux \<le> lpi      then (lb_cos prec ux, ub_cos prec lx)
  1162   else if - lpi \<le> lx \<and> ux \<le> lpi  then (min (lb_cos prec (-lx)) (lb_cos prec ux), Float 1 0)
  1163   else if 0 \<le> lx \<and> ux \<le> 2 * lpi  then (Float -1 0, max (ub_cos prec lx) (ub_cos prec (- (ux - 2 * lpi))))
  1164   else if -2 * lpi \<le> lx \<and> ux \<le> 0 then (Float -1 0, max (ub_cos prec (lx + 2 * lpi)) (ub_cos prec (-ux)))
  1165                                  else (Float -1 0, Float 1 0))"
  1166 
  1167 lemma floor_int:
  1168   obtains k :: int where "real k = (floor_fl f)"
  1169 proof -
  1170   assume *: "\<And> k :: int. real k = (floor_fl f) \<Longrightarrow> thesis"
  1171   obtain m e where fl: "Float m e = floor_fl f" by (cases "floor_fl f", auto)
  1172   from floor_pos_exp[OF this]
  1173   have "real (m* 2^(nat e)) = (floor_fl f)"
  1174     by (auto simp add: fl[symmetric] real_of_float_def pow2_def)
  1175   from *[OF this] show thesis by blast
  1176 qed
  1177 
  1178 lemma float_remove_real_numeral[simp]: "(number_of k :: float) = (number_of k :: real)"
  1179 proof -
  1180   have "(number_of k :: float) = real k"
  1181     unfolding number_of_float_def real_of_float_def pow2_def by auto
  1182   also have "\<dots> = (number_of k :: int)"
  1183     by (simp add: number_of_is_id)
  1184   finally show ?thesis by auto
  1185 qed
  1186 
  1187 lemma cos_periodic_nat[simp]: fixes n :: nat shows "cos (x + n * (2 * pi)) = cos x"
  1188 proof (induct n arbitrary: x)
  1189   case (Suc n)
  1190   have split_pi_off: "x + (Suc n) * (2 * pi) = (x + n * (2 * pi)) + 2 * pi"
  1191     unfolding Suc_eq_plus1 real_of_nat_add real_of_one left_distrib by auto
  1192   show ?case unfolding split_pi_off using Suc by auto
  1193 qed auto
  1194 
  1195 lemma cos_periodic_int[simp]: fixes i :: int shows "cos (x + i * (2 * pi)) = cos x"
  1196 proof (cases "0 \<le> i")
  1197   case True hence i_nat: "real i = nat i" by auto
  1198   show ?thesis unfolding i_nat by auto
  1199 next
  1200   case False hence i_nat: "i = - real (nat (-i))" by auto
  1201   have "cos x = cos (x + i * (2 * pi) - i * (2 * pi))" by auto
  1202   also have "\<dots> = cos (x + i * (2 * pi))"
  1203     unfolding i_nat mult_minus_left diff_minus_eq_add by (rule cos_periodic_nat)
  1204   finally show ?thesis by auto
  1205 qed
  1206 
  1207 lemma bnds_cos: "\<forall> (x::real) lx ux. (l, u) = bnds_cos prec lx ux \<and> x \<in> {lx .. ux} \<longrightarrow> l \<le> cos x \<and> cos x \<le> u"
  1208 proof ((rule allI | rule impI | erule conjE) +)
  1209   fix x :: real fix lx ux
  1210   assume bnds: "(l, u) = bnds_cos prec lx ux" and x: "x \<in> {lx .. ux}"
  1211 
  1212   let ?lpi = "round_down prec (lb_pi prec)"
  1213   let ?upi = "round_up prec (ub_pi prec)"
  1214   let ?k = "floor_fl (float_divr prec (lx + ?lpi) (2 * ?lpi))"
  1215   let ?lx = "lx - ?k * 2 * (if ?k < 0 then ?lpi else ?upi)"
  1216   let ?ux = "ux - ?k * 2 * (if ?k < 0 then ?upi else ?lpi)"
  1217 
  1218   obtain k :: int where k: "k = real ?k" using floor_int .
  1219 
  1220   have upi: "pi \<le> ?upi" and lpi: "?lpi \<le> pi"
  1221     using round_up[of "ub_pi prec" prec] pi_boundaries[of prec]
  1222           round_down[of prec "lb_pi prec"] by auto
  1223   hence "?lx \<le> x - k * (2 * pi) \<and> x - k * (2 * pi) \<le> ?ux"
  1224     using x by (cases "k = 0") (auto intro!: add_mono
  1225                 simp add: diff_minus k[symmetric] less_float_def)
  1226   note lx = this[THEN conjunct1] and ux = this[THEN conjunct2]
  1227   hence lx_less_ux: "?lx \<le> real ?ux" by (rule order_trans)
  1228 
  1229   { assume "- ?lpi \<le> ?lx" and x_le_0: "x - k * (2 * pi) \<le> 0"
  1230     with lpi[THEN le_imp_neg_le] lx
  1231     have pi_lx: "- pi \<le> ?lx" and lx_0: "real ?lx \<le> 0"
  1232       by (simp_all add: le_float_def)
  1233 
  1234     have "(lb_cos prec (- ?lx)) \<le> cos (real (- ?lx))"
  1235       using lb_cos_minus[OF pi_lx lx_0] by simp
  1236     also have "\<dots> \<le> cos (x + (-k) * (2 * pi))"
  1237       using cos_monotone_minus_pi_0'[OF pi_lx lx x_le_0]
  1238       by (simp only: real_of_float_minus real_of_int_minus
  1239         cos_minus diff_minus mult_minus_left)
  1240     finally have "(lb_cos prec (- ?lx)) \<le> cos x"
  1241       unfolding cos_periodic_int . }
  1242   note negative_lx = this
  1243 
  1244   { assume "0 \<le> ?lx" and pi_x: "x - k * (2 * pi) \<le> pi"
  1245     with lx
  1246     have pi_lx: "?lx \<le> pi" and lx_0: "0 \<le> real ?lx"
  1247       by (auto simp add: le_float_def)
  1248 
  1249     have "cos (x + (-k) * (2 * pi)) \<le> cos ?lx"
  1250       using cos_monotone_0_pi'[OF lx_0 lx pi_x]
  1251       by (simp only: real_of_float_minus real_of_int_minus
  1252         cos_minus diff_minus mult_minus_left)
  1253     also have "\<dots> \<le> (ub_cos prec ?lx)"
  1254       using lb_cos[OF lx_0 pi_lx] by simp
  1255     finally have "cos x \<le> (ub_cos prec ?lx)"
  1256       unfolding cos_periodic_int . }
  1257   note positive_lx = this
  1258 
  1259   { assume pi_x: "- pi \<le> x - k * (2 * pi)" and "?ux \<le> 0"
  1260     with ux
  1261     have pi_ux: "- pi \<le> ?ux" and ux_0: "real ?ux \<le> 0"
  1262       by (simp_all add: le_float_def)
  1263 
  1264     have "cos (x + (-k) * (2 * pi)) \<le> cos (real (- ?ux))"
  1265       using cos_monotone_minus_pi_0'[OF pi_x ux ux_0]
  1266       by (simp only: real_of_float_minus real_of_int_minus
  1267           cos_minus diff_minus mult_minus_left)
  1268     also have "\<dots> \<le> (ub_cos prec (- ?ux))"
  1269       using lb_cos_minus[OF pi_ux ux_0, of prec] by simp
  1270     finally have "cos x \<le> (ub_cos prec (- ?ux))"
  1271       unfolding cos_periodic_int . }
  1272   note negative_ux = this
  1273 
  1274   { assume "?ux \<le> ?lpi" and x_ge_0: "0 \<le> x - k * (2 * pi)"
  1275     with lpi ux
  1276     have pi_ux: "?ux \<le> pi" and ux_0: "0 \<le> real ?ux"
  1277       by (simp_all add: le_float_def)
  1278 
  1279     have "(lb_cos prec ?ux) \<le> cos ?ux"
  1280       using lb_cos[OF ux_0 pi_ux] by simp
  1281     also have "\<dots> \<le> cos (x + (-k) * (2 * pi))"
  1282       using cos_monotone_0_pi'[OF x_ge_0 ux pi_ux]
  1283       by (simp only: real_of_float_minus real_of_int_minus
  1284         cos_minus diff_minus mult_minus_left)
  1285     finally have "(lb_cos prec ?ux) \<le> cos x"
  1286       unfolding cos_periodic_int . }
  1287   note positive_ux = this
  1288 
  1289   show "l \<le> cos x \<and> cos x \<le> u"
  1290   proof (cases "- ?lpi \<le> ?lx \<and> ?ux \<le> 0")
  1291     case True with bnds
  1292     have l: "l = lb_cos prec (-?lx)"
  1293       and u: "u = ub_cos prec (-?ux)"
  1294       by (auto simp add: bnds_cos_def Let_def)
  1295 
  1296     from True lpi[THEN le_imp_neg_le] lx ux
  1297     have "- pi \<le> x - k * (2 * pi)"
  1298       and "x - k * (2 * pi) \<le> 0"
  1299       by (auto simp add: le_float_def)
  1300     with True negative_ux negative_lx
  1301     show ?thesis unfolding l u by simp
  1302   next case False note 1 = this show ?thesis
  1303   proof (cases "0 \<le> ?lx \<and> ?ux \<le> ?lpi")
  1304     case True with bnds 1
  1305     have l: "l = lb_cos prec ?ux"
  1306       and u: "u = ub_cos prec ?lx"
  1307       by (auto simp add: bnds_cos_def Let_def)
  1308 
  1309     from True lpi lx ux
  1310     have "0 \<le> x - k * (2 * pi)"
  1311       and "x - k * (2 * pi) \<le> pi"
  1312       by (auto simp add: le_float_def)
  1313     with True positive_ux positive_lx
  1314     show ?thesis unfolding l u by simp
  1315   next case False note 2 = this show ?thesis
  1316   proof (cases "- ?lpi \<le> ?lx \<and> ?ux \<le> ?lpi")
  1317     case True note Cond = this with bnds 1 2
  1318     have l: "l = min (lb_cos prec (-?lx)) (lb_cos prec ?ux)"
  1319       and u: "u = Float 1 0"
  1320       by (auto simp add: bnds_cos_def Let_def)
  1321 
  1322     show ?thesis unfolding u l using negative_lx positive_ux Cond
  1323       by (cases "x - k * (2 * pi) < 0", simp_all add: real_of_float_min)
  1324   next case False note 3 = this show ?thesis
  1325   proof (cases "0 \<le> ?lx \<and> ?ux \<le> 2 * ?lpi")
  1326     case True note Cond = this with bnds 1 2 3
  1327     have l: "l = Float -1 0"
  1328       and u: "u = max (ub_cos prec ?lx) (ub_cos prec (- (?ux - 2 * ?lpi)))"
  1329       by (auto simp add: bnds_cos_def Let_def)
  1330 
  1331     have "cos x \<le> real u"
  1332     proof (cases "x - k * (2 * pi) < pi")
  1333       case True hence "x - k * (2 * pi) \<le> pi" by simp
  1334       from positive_lx[OF Cond[THEN conjunct1] this]
  1335       show ?thesis unfolding u by (simp add: real_of_float_max)
  1336     next
  1337       case False hence "pi \<le> x - k * (2 * pi)" by simp
  1338       hence pi_x: "- pi \<le> x - k * (2 * pi) - 2 * pi" by simp
  1339 
  1340       have "?ux \<le> 2 * pi" using Cond lpi by (auto simp add: le_float_def)
  1341       hence "x - k * (2 * pi) - 2 * pi \<le> 0" using ux by simp
  1342 
  1343       have ux_0: "real (?ux - 2 * ?lpi) \<le> 0"
  1344         using Cond by (auto simp add: le_float_def)
  1345 
  1346       from 2 and Cond have "\<not> ?ux \<le> ?lpi" by auto
  1347       hence "- ?lpi \<le> ?ux - 2 * ?lpi" by (auto simp add: le_float_def)
  1348       hence pi_ux: "- pi \<le> (?ux - 2 * ?lpi)"
  1349         using lpi[THEN le_imp_neg_le] by (auto simp add: le_float_def)
  1350 
  1351       have x_le_ux: "x - k * (2 * pi) - 2 * pi \<le> (?ux - 2 * ?lpi)"
  1352         using ux lpi by auto
  1353 
  1354       have "cos x = cos (x + (-k) * (2 * pi) + (-1::int) * (2 * pi))"
  1355         unfolding cos_periodic_int ..
  1356       also have "\<dots> \<le> cos ((?ux - 2 * ?lpi))"
  1357         using cos_monotone_minus_pi_0'[OF pi_x x_le_ux ux_0]
  1358         by (simp only: real_of_float_minus real_of_int_minus real_of_one
  1359             number_of_Min diff_minus mult_minus_left mult_1_left)
  1360       also have "\<dots> = cos ((- (?ux - 2 * ?lpi)))"
  1361         unfolding real_of_float_minus cos_minus ..
  1362       also have "\<dots> \<le> (ub_cos prec (- (?ux - 2 * ?lpi)))"
  1363         using lb_cos_minus[OF pi_ux ux_0] by simp
  1364       finally show ?thesis unfolding u by (simp add: real_of_float_max)
  1365     qed
  1366     thus ?thesis unfolding l by auto
  1367   next case False note 4 = this show ?thesis
  1368   proof (cases "-2 * ?lpi \<le> ?lx \<and> ?ux \<le> 0")
  1369     case True note Cond = this with bnds 1 2 3 4
  1370     have l: "l = Float -1 0"
  1371       and u: "u = max (ub_cos prec (?lx + 2 * ?lpi)) (ub_cos prec (-?ux))"
  1372       by (auto simp add: bnds_cos_def Let_def)
  1373 
  1374     have "cos x \<le> u"
  1375     proof (cases "-pi < x - k * (2 * pi)")
  1376       case True hence "-pi \<le> x - k * (2 * pi)" by simp
  1377       from negative_ux[OF this Cond[THEN conjunct2]]
  1378       show ?thesis unfolding u by (simp add: real_of_float_max)
  1379     next
  1380       case False hence "x - k * (2 * pi) \<le> -pi" by simp
  1381       hence pi_x: "x - k * (2 * pi) + 2 * pi \<le> pi" by simp
  1382 
  1383       have "-2 * pi \<le> ?lx" using Cond lpi by (auto simp add: le_float_def)
  1384 
  1385       hence "0 \<le> x - k * (2 * pi) + 2 * pi" using lx by simp
  1386 
  1387       have lx_0: "0 \<le> real (?lx + 2 * ?lpi)"
  1388         using Cond lpi by (auto simp add: le_float_def)
  1389 
  1390       from 1 and Cond have "\<not> -?lpi \<le> ?lx" by auto
  1391       hence "?lx + 2 * ?lpi \<le> ?lpi" by (auto simp add: le_float_def)
  1392       hence pi_lx: "(?lx + 2 * ?lpi) \<le> pi"
  1393         using lpi[THEN le_imp_neg_le] by (auto simp add: le_float_def)
  1394 
  1395       have lx_le_x: "(?lx + 2 * ?lpi) \<le> x - k * (2 * pi) + 2 * pi"
  1396         using lx lpi by auto
  1397 
  1398       have "cos x = cos (x + (-k) * (2 * pi) + (1 :: int) * (2 * pi))"
  1399         unfolding cos_periodic_int ..
  1400       also have "\<dots> \<le> cos ((?lx + 2 * ?lpi))"
  1401         using cos_monotone_0_pi'[OF lx_0 lx_le_x pi_x]
  1402         by (simp only: real_of_float_minus real_of_int_minus real_of_one
  1403           number_of_Min diff_minus mult_minus_left mult_1_left)
  1404       also have "\<dots> \<le> (ub_cos prec (?lx + 2 * ?lpi))"
  1405         using lb_cos[OF lx_0 pi_lx] by simp
  1406       finally show ?thesis unfolding u by (simp add: real_of_float_max)
  1407     qed
  1408     thus ?thesis unfolding l by auto
  1409   next
  1410     case False with bnds 1 2 3 4 show ?thesis by (auto simp add: bnds_cos_def Let_def)
  1411   qed qed qed qed qed
  1412 qed
  1413 
  1414 section "Exponential function"
  1415 
  1416 subsection "Compute the series of the exponential function"
  1417 
  1418 fun ub_exp_horner :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> float \<Rightarrow> float" and lb_exp_horner :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> float \<Rightarrow> float" where
  1419 "ub_exp_horner prec 0 i k x       = 0" |
  1420 "ub_exp_horner prec (Suc n) i k x = rapprox_rat prec 1 (int k) + x * lb_exp_horner prec n (i + 1) (k * i) x" |
  1421 "lb_exp_horner prec 0 i k x       = 0" |
  1422 "lb_exp_horner prec (Suc n) i k x = lapprox_rat prec 1 (int k) + x * ub_exp_horner prec n (i + 1) (k * i) x"
  1423 
  1424 lemma bnds_exp_horner: assumes "real x \<le> 0"
  1425   shows "exp x \<in> { lb_exp_horner prec (get_even n) 1 1 x .. ub_exp_horner prec (get_odd n) 1 1 x }"
  1426 proof -
  1427   { fix n
  1428     have F: "\<And> m. ((\<lambda>i. i + 1) ^^ n) m = n + m" by (induct n, auto)
  1429     have "fact (Suc n) = fact n * ((\<lambda>i. i + 1) ^^ n) 1" unfolding F by auto } note f_eq = this
  1430 
  1431   note bounds = horner_bounds_nonpos[where f="fact" and lb="lb_exp_horner prec" and ub="ub_exp_horner prec" and j'=0 and s=1,
  1432     OF assms f_eq lb_exp_horner.simps ub_exp_horner.simps]
  1433 
  1434   { have "lb_exp_horner prec (get_even n) 1 1 x \<le> (\<Sum>j = 0..<get_even n. 1 / real (fact j) * real x ^ j)"
  1435       using bounds(1) by auto
  1436     also have "\<dots> \<le> exp x"
  1437     proof -
  1438       obtain t where "\<bar>t\<bar> \<le> \<bar>real x\<bar>" and "exp x = (\<Sum>m = 0..<get_even n. real x ^ m / real (fact m)) + exp t / real (fact (get_even n)) * (real x) ^ (get_even n)"
  1439         using Maclaurin_exp_le by blast
  1440       moreover have "0 \<le> exp t / real (fact (get_even n)) * (real x) ^ (get_even n)"
  1441         by (auto intro!: mult_nonneg_nonneg divide_nonneg_pos simp add: get_even zero_le_even_power exp_gt_zero)
  1442       ultimately show ?thesis
  1443         using get_odd exp_gt_zero by (auto intro!: mult_nonneg_nonneg)
  1444     qed
  1445     finally have "lb_exp_horner prec (get_even n) 1 1 x \<le> exp x" .
  1446   } moreover
  1447   {
  1448     have x_less_zero: "real x ^ get_odd n \<le> 0"
  1449     proof (cases "real x = 0")
  1450       case True
  1451       have "(get_odd n) \<noteq> 0" using get_odd[THEN odd_pos] by auto
  1452       thus ?thesis unfolding True power_0_left by auto
  1453     next
  1454       case False hence "real x < 0" using `real x \<le> 0` by auto
  1455       show ?thesis by (rule less_imp_le, auto simp add: power_less_zero_eq get_odd `real x < 0`)
  1456     qed
  1457 
  1458     obtain t where "\<bar>t\<bar> \<le> \<bar>real x\<bar>" and "exp x = (\<Sum>m = 0..<get_odd n. (real x) ^ m / real (fact m)) + exp t / real (fact (get_odd n)) * (real x) ^ (get_odd n)"
  1459       using Maclaurin_exp_le by blast
  1460     moreover have "exp t / real (fact (get_odd n)) * (real x) ^ (get_odd n) \<le> 0"
  1461       by (auto intro!: mult_nonneg_nonpos divide_nonpos_pos simp add: x_less_zero exp_gt_zero)
  1462     ultimately have "exp x \<le> (\<Sum>j = 0..<get_odd n. 1 / real (fact j) * real x ^ j)"
  1463       using get_odd exp_gt_zero by (auto intro!: mult_nonneg_nonneg)
  1464     also have "\<dots> \<le> ub_exp_horner prec (get_odd n) 1 1 x"
  1465       using bounds(2) by auto
  1466     finally have "exp x \<le> ub_exp_horner prec (get_odd n) 1 1 x" .
  1467   } ultimately show ?thesis by auto
  1468 qed
  1469 
  1470 subsection "Compute the exponential function on the entire domain"
  1471 
  1472 function ub_exp :: "nat \<Rightarrow> float \<Rightarrow> float" and lb_exp :: "nat \<Rightarrow> float \<Rightarrow> float" where
  1473 "lb_exp prec x = (if 0 < x then float_divl prec 1 (ub_exp prec (-x))
  1474              else let
  1475                 horner = (\<lambda> x. let  y = lb_exp_horner prec (get_even (prec + 2)) 1 1 x  in if y \<le> 0 then Float 1 -2 else y)
  1476              in if x < - 1 then (case floor_fl x of (Float m e) \<Rightarrow> (horner (float_divl prec x (- Float m e))) ^ (nat (-m) * 2 ^ nat e))
  1477                            else horner x)" |
  1478 "ub_exp prec x = (if 0 < x    then float_divr prec 1 (lb_exp prec (-x))
  1479              else if x < - 1  then (case floor_fl x of (Float m e) \<Rightarrow>
  1480                                     (ub_exp_horner prec (get_odd (prec + 2)) 1 1 (float_divr prec x (- Float m e))) ^ (nat (-m) * 2 ^ nat e))
  1481                               else ub_exp_horner prec (get_odd (prec + 2)) 1 1 x)"
  1482 by pat_completeness auto
  1483 termination by (relation "measure (\<lambda> v. let (prec, x) = sum_case id id v in (if 0 < x then 1 else 0))", auto simp add: less_float_def)
  1484 
  1485 lemma exp_m1_ge_quarter: "(1 / 4 :: real) \<le> exp (- 1)"
  1486 proof -
  1487   have eq4: "4 = Suc (Suc (Suc (Suc 0)))" by auto
  1488 
  1489   have "1 / 4 = (Float 1 -2)" unfolding Float_num by auto
  1490   also have "\<dots> \<le> lb_exp_horner 1 (get_even 4) 1 1 (- 1)"
  1491     unfolding get_even_def eq4
  1492     by (auto simp add: lapprox_posrat_def rapprox_posrat_def normfloat.simps)
  1493   also have "\<dots> \<le> exp (- 1 :: float)" using bnds_exp_horner[where x="- 1"] by auto
  1494   finally show ?thesis unfolding real_of_float_minus real_of_float_1 .
  1495 qed
  1496 
  1497 lemma lb_exp_pos: assumes "\<not> 0 < x" shows "0 < lb_exp prec x"
  1498 proof -
  1499   let "?lb_horner x" = "lb_exp_horner prec (get_even (prec + 2)) 1 1 x"
  1500   let "?horner x" = "let  y = ?lb_horner x  in if y \<le> 0 then Float 1 -2 else y"
  1501   have pos_horner: "\<And> x. 0 < ?horner x" unfolding Let_def by (cases "?lb_horner x \<le> 0", auto simp add: le_float_def less_float_def)
  1502   moreover { fix x :: float fix num :: nat
  1503     have "0 < real (?horner x) ^ num" using `0 < ?horner x`[unfolded less_float_def real_of_float_0] by (rule zero_less_power)
  1504     also have "\<dots> = (?horner x) ^ num" using float_power by auto
  1505     finally have "0 < real ((?horner x) ^ num)" .
  1506   }
  1507   ultimately show ?thesis
  1508     unfolding lb_exp.simps if_not_P[OF `\<not> 0 < x`] Let_def
  1509     by (cases "floor_fl x", cases "x < - 1", auto simp add: float_power le_float_def less_float_def)
  1510 qed
  1511 
  1512 lemma exp_boundaries': assumes "x \<le> 0"
  1513   shows "exp x \<in> { (lb_exp prec x) .. (ub_exp prec x)}"
  1514 proof -
  1515   let "?lb_exp_horner x" = "lb_exp_horner prec (get_even (prec + 2)) 1 1 x"
  1516   let "?ub_exp_horner x" = "ub_exp_horner prec (get_odd (prec + 2)) 1 1 x"
  1517 
  1518   have "real x \<le> 0" and "\<not> x > 0" using `x \<le> 0` unfolding le_float_def less_float_def by auto
  1519   show ?thesis
  1520   proof (cases "x < - 1")
  1521     case False hence "- 1 \<le> real x" unfolding less_float_def by auto
  1522     show ?thesis
  1523     proof (cases "?lb_exp_horner x \<le> 0")
  1524       from `\<not> x < - 1` have "- 1 \<le> real x" unfolding less_float_def by auto
  1525       hence "exp (- 1) \<le> exp x" unfolding exp_le_cancel_iff .
  1526       from order_trans[OF exp_m1_ge_quarter this]
  1527       have "Float 1 -2 \<le> exp x" unfolding Float_num .
  1528       moreover case True
  1529       ultimately show ?thesis using bnds_exp_horner `real x \<le> 0` `\<not> x > 0` `\<not> x < - 1` by auto
  1530     next
  1531       case False thus ?thesis using bnds_exp_horner `real x \<le> 0` `\<not> x > 0` `\<not> x < - 1` by (auto simp add: Let_def)
  1532     qed
  1533   next
  1534     case True
  1535 
  1536     obtain m e where Float_floor: "floor_fl x = Float m e" by (cases "floor_fl x", auto)
  1537     let ?num = "nat (- m) * 2 ^ nat e"
  1538 
  1539     have "real (floor_fl x) < - 1" using floor_fl `x < - 1` unfolding le_float_def less_float_def real_of_float_minus real_of_float_1 by (rule order_le_less_trans)
  1540     hence "real (floor_fl x) < 0" unfolding Float_floor real_of_float_simp using zero_less_pow2[of xe] by auto
  1541     hence "m < 0"
  1542       unfolding less_float_def real_of_float_0 Float_floor real_of_float_simp
  1543       unfolding pos_prod_lt[OF zero_less_pow2[of e], unfolded mult_commute] by auto
  1544     hence "1 \<le> - m" by auto
  1545     hence "0 < nat (- m)" by auto
  1546     moreover
  1547     have "0 \<le> e" using floor_pos_exp Float_floor[symmetric] by auto
  1548     hence "(0::nat) < 2 ^ nat e" by auto
  1549     ultimately have "0 < ?num"  by auto
  1550     hence "real ?num \<noteq> 0" by auto
  1551     have e_nat: "(nat e) = e" using `0 \<le> e` by auto
  1552     have num_eq: "real ?num = - floor_fl x" using `0 < nat (- m)`
  1553       unfolding Float_floor real_of_float_minus real_of_float_simp real_of_nat_mult pow2_int[of "nat e", unfolded e_nat] real_of_nat_power by auto
  1554     have "0 < - floor_fl x" using `0 < ?num`[unfolded real_of_nat_less_iff[symmetric]] unfolding less_float_def num_eq[symmetric] real_of_float_0 real_of_nat_zero .
  1555     hence "real (floor_fl x) < 0" unfolding less_float_def by auto
  1556 
  1557     have "exp x \<le> ub_exp prec x"
  1558     proof -
  1559       have div_less_zero: "real (float_divr prec x (- floor_fl x)) \<le> 0"
  1560         using float_divr_nonpos_pos_upper_bound[OF `x \<le> 0` `0 < - floor_fl x`] unfolding le_float_def real_of_float_0 .
  1561 
  1562       have "exp x = exp (?num * (x / ?num))" using `real ?num \<noteq> 0` by auto
  1563       also have "\<dots> = exp (x / ?num) ^ ?num" unfolding exp_real_of_nat_mult ..
  1564       also have "\<dots> \<le> exp (float_divr prec x (- floor_fl x)) ^ ?num" unfolding num_eq
  1565         by (rule power_mono, rule exp_le_cancel_iff[THEN iffD2], rule float_divr) auto
  1566       also have "\<dots> \<le> (?ub_exp_horner (float_divr prec x (- floor_fl x))) ^ ?num" unfolding float_power
  1567         by (rule power_mono, rule bnds_exp_horner[OF div_less_zero, unfolded atLeastAtMost_iff, THEN conjunct2], auto)
  1568       finally show ?thesis unfolding ub_exp.simps if_not_P[OF `\<not> 0 < x`] if_P[OF `x < - 1`] float.cases Float_floor Let_def .
  1569     qed
  1570     moreover
  1571     have "lb_exp prec x \<le> exp x"
  1572     proof -
  1573       let ?divl = "float_divl prec x (- Float m e)"
  1574       let ?horner = "?lb_exp_horner ?divl"
  1575 
  1576       show ?thesis
  1577       proof (cases "?horner \<le> 0")
  1578         case False hence "0 \<le> real ?horner" unfolding le_float_def by auto
  1579 
  1580         have div_less_zero: "real (float_divl prec x (- floor_fl x)) \<le> 0"
  1581           using `real (floor_fl x) < 0` `real x \<le> 0` by (auto intro!: order_trans[OF float_divl] divide_nonpos_neg)
  1582 
  1583         have "(?lb_exp_horner (float_divl prec x (- floor_fl x))) ^ ?num \<le>
  1584           exp (float_divl prec x (- floor_fl x)) ^ ?num" unfolding float_power
  1585           using `0 \<le> real ?horner`[unfolded Float_floor[symmetric]] bnds_exp_horner[OF div_less_zero, unfolded atLeastAtMost_iff, THEN conjunct1] by (auto intro!: power_mono)
  1586         also have "\<dots> \<le> exp (x / ?num) ^ ?num" unfolding num_eq
  1587           using float_divl by (auto intro!: power_mono simp del: real_of_float_minus)
  1588         also have "\<dots> = exp (?num * (x / ?num))" unfolding exp_real_of_nat_mult ..
  1589         also have "\<dots> = exp x" using `real ?num \<noteq> 0` by auto
  1590         finally show ?thesis
  1591           unfolding lb_exp.simps if_not_P[OF `\<not> 0 < x`] if_P[OF `x < - 1`] float.cases Float_floor Let_def if_not_P[OF False] by auto
  1592       next
  1593         case True
  1594         have "real (floor_fl x) \<noteq> 0" and "real (floor_fl x) \<le> 0" using `real (floor_fl x) < 0` by auto
  1595         from divide_right_mono_neg[OF floor_fl[of x] `real (floor_fl x) \<le> 0`, unfolded divide_self[OF `real (floor_fl x) \<noteq> 0`]]
  1596         have "- 1 \<le> x / (- floor_fl x)" unfolding real_of_float_minus by auto
  1597         from order_trans[OF exp_m1_ge_quarter this[unfolded exp_le_cancel_iff[where x="- 1", symmetric]]]
  1598         have "Float 1 -2 \<le> exp (x / (- floor_fl x))" unfolding Float_num .
  1599         hence "real (Float 1 -2) ^ ?num \<le> exp (x / (- floor_fl x)) ^ ?num"
  1600           by (auto intro!: power_mono simp add: Float_num)
  1601         also have "\<dots> = exp x" unfolding num_eq exp_real_of_nat_mult[symmetric] using `real (floor_fl x) \<noteq> 0` by auto
  1602         finally show ?thesis
  1603           unfolding lb_exp.simps if_not_P[OF `\<not> 0 < x`] if_P[OF `x < - 1`] float.cases Float_floor Let_def if_P[OF True] float_power .
  1604       qed
  1605     qed
  1606     ultimately show ?thesis by auto
  1607   qed
  1608 qed
  1609 
  1610 lemma exp_boundaries: "exp x \<in> { lb_exp prec x .. ub_exp prec x }"
  1611 proof -
  1612   show ?thesis
  1613   proof (cases "0 < x")
  1614     case False hence "x \<le> 0" unfolding less_float_def le_float_def by auto
  1615     from exp_boundaries'[OF this] show ?thesis .
  1616   next
  1617     case True hence "-x \<le> 0" unfolding less_float_def le_float_def by auto
  1618 
  1619     have "lb_exp prec x \<le> exp x"
  1620     proof -
  1621       from exp_boundaries'[OF `-x \<le> 0`]
  1622       have ub_exp: "exp (- real x) \<le> ub_exp prec (-x)" unfolding atLeastAtMost_iff real_of_float_minus by auto
  1623 
  1624       have "float_divl prec 1 (ub_exp prec (-x)) \<le> 1 / ub_exp prec (-x)" using float_divl[where x=1] by auto
  1625       also have "\<dots> \<le> exp x"
  1626         using ub_exp[unfolded inverse_le_iff_le[OF order_less_le_trans[OF exp_gt_zero ub_exp] exp_gt_zero, symmetric]]
  1627         unfolding exp_minus nonzero_inverse_inverse_eq[OF exp_not_eq_zero] inverse_eq_divide by auto
  1628       finally show ?thesis unfolding lb_exp.simps if_P[OF True] .
  1629     qed
  1630     moreover
  1631     have "exp x \<le> ub_exp prec x"
  1632     proof -
  1633       have "\<not> 0 < -x" using `0 < x` unfolding less_float_def by auto
  1634 
  1635       from exp_boundaries'[OF `-x \<le> 0`]
  1636       have lb_exp: "lb_exp prec (-x) \<le> exp (- real x)" unfolding atLeastAtMost_iff real_of_float_minus by auto
  1637 
  1638       have "exp x \<le> (1 :: float) / lb_exp prec (-x)"
  1639         using lb_exp[unfolded inverse_le_iff_le[OF exp_gt_zero lb_exp_pos[OF `\<not> 0 < -x`, unfolded less_float_def real_of_float_0],
  1640                                                 symmetric]]
  1641         unfolding exp_minus nonzero_inverse_inverse_eq[OF exp_not_eq_zero] inverse_eq_divide real_of_float_1 by auto
  1642       also have "\<dots> \<le> float_divr prec 1 (lb_exp prec (-x))" using float_divr .
  1643       finally show ?thesis unfolding ub_exp.simps if_P[OF True] .
  1644     qed
  1645     ultimately show ?thesis by auto
  1646   qed
  1647 qed
  1648 
  1649 lemma bnds_exp: "\<forall> (x::real) lx ux. (l, u) = (lb_exp prec lx, ub_exp prec ux) \<and> x \<in> {lx .. ux} \<longrightarrow> l \<le> exp x \<and> exp x \<le> u"
  1650 proof (rule allI, rule allI, rule allI, rule impI)
  1651   fix x::real and lx ux
  1652   assume "(l, u) = (lb_exp prec lx, ub_exp prec ux) \<and> x \<in> {lx .. ux}"
  1653   hence l: "lb_exp prec lx = l " and u: "ub_exp prec ux = u" and x: "x \<in> {lx .. ux}" by auto
  1654 
  1655   { from exp_boundaries[of lx prec, unfolded l]
  1656     have "l \<le> exp lx" by (auto simp del: lb_exp.simps)
  1657     also have "\<dots> \<le> exp x" using x by auto
  1658     finally have "l \<le> exp x" .
  1659   } moreover
  1660   { have "exp x \<le> exp ux" using x by auto
  1661     also have "\<dots> \<le> u" using exp_boundaries[of ux prec, unfolded u] by (auto simp del: ub_exp.simps)
  1662     finally have "exp x \<le> u" .
  1663   } ultimately show "l \<le> exp x \<and> exp x \<le> u" ..
  1664 qed
  1665 
  1666 section "Logarithm"
  1667 
  1668 subsection "Compute the logarithm series"
  1669 
  1670 fun ub_ln_horner :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> float \<Rightarrow> float"
  1671 and lb_ln_horner :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> float \<Rightarrow> float" where
  1672 "ub_ln_horner prec 0 i x       = 0" |
  1673 "ub_ln_horner prec (Suc n) i x = rapprox_rat prec 1 (int i) - x * lb_ln_horner prec n (Suc i) x" |
  1674 "lb_ln_horner prec 0 i x       = 0" |
  1675 "lb_ln_horner prec (Suc n) i x = lapprox_rat prec 1 (int i) - x * ub_ln_horner prec n (Suc i) x"
  1676 
  1677 lemma ln_bounds:
  1678   assumes "0 \<le> x" and "x < 1"
  1679   shows "(\<Sum>i=0..<2*n. -1^i * (1 / real (i + 1)) * x ^ (Suc i)) \<le> ln (x + 1)" (is "?lb")
  1680   and "ln (x + 1) \<le> (\<Sum>i=0..<2*n + 1. -1^i * (1 / real (i + 1)) * x ^ (Suc i))" (is "?ub")
  1681 proof -
  1682   let "?a n" = "(1/real (n +1)) * x ^ (Suc n)"
  1683 
  1684   have ln_eq: "(\<Sum> i. -1^i * ?a i) = ln (x + 1)"
  1685     using ln_series[of "x + 1"] `0 \<le> x` `x < 1` by auto
  1686 
  1687   have "norm x < 1" using assms by auto
  1688   have "?a ----> 0" unfolding Suc_eq_plus1[symmetric] inverse_eq_divide[symmetric]
  1689     using LIMSEQ_mult[OF LIMSEQ_inverse_real_of_nat LIMSEQ_Suc[OF LIMSEQ_power_zero[OF `norm x < 1`]]] by auto
  1690   { fix n have "0 \<le> ?a n" by (rule mult_nonneg_nonneg, auto intro!: mult_nonneg_nonneg simp add: `0 \<le> x`) }
  1691   { fix n have "?a (Suc n) \<le> ?a n" unfolding inverse_eq_divide[symmetric]
  1692     proof (rule mult_mono)
  1693       show "0 \<le> x ^ Suc (Suc n)" by (auto intro!: mult_nonneg_nonneg simp add: `0 \<le> x`)
  1694       have "x ^ Suc (Suc n) \<le> x ^ Suc n * 1" unfolding power_Suc2 mult_assoc[symmetric]
  1695         by (rule mult_left_mono, fact less_imp_le[OF `x < 1`], auto intro!: mult_nonneg_nonneg simp add: `0 \<le> x`)
  1696       thus "x ^ Suc (Suc n) \<le> x ^ Suc n" by auto
  1697     qed auto }
  1698   from summable_Leibniz'(2,4)[OF `?a ----> 0` `\<And>n. 0 \<le> ?a n`, OF `\<And>n. ?a (Suc n) \<le> ?a n`, unfolded ln_eq]
  1699   show "?lb" and "?ub" by auto
  1700 qed
  1701 
  1702 lemma ln_float_bounds:
  1703   assumes "0 \<le> real x" and "real x < 1"
  1704   shows "x * lb_ln_horner prec (get_even n) 1 x \<le> ln (x + 1)" (is "?lb \<le> ?ln")
  1705   and "ln (x + 1) \<le> x * ub_ln_horner prec (get_odd n) 1 x" (is "?ln \<le> ?ub")
  1706 proof -
  1707   obtain ev where ev: "get_even n = 2 * ev" using get_even_double ..
  1708   obtain od where od: "get_odd n = 2 * od + 1" using get_odd_double ..
  1709 
  1710   let "?s n" = "-1^n * (1 / real (1 + n)) * (real x)^(Suc n)"
  1711 
  1712   have "?lb \<le> setsum ?s {0 ..< 2 * ev}" unfolding power_Suc2 mult_assoc[symmetric] real_of_float_mult setsum_left_distrib[symmetric] unfolding mult_commute[of "real x"] ev
  1713     using horner_bounds(1)[where G="\<lambda> i k. Suc k" and F="\<lambda>x. x" and f="\<lambda>x. x" and lb="\<lambda>n i k x. lb_ln_horner prec n k x" and ub="\<lambda>n i k x. ub_ln_horner prec n k x" and j'=1 and n="2*ev",
  1714       OF `0 \<le> real x` refl lb_ln_horner.simps ub_ln_horner.simps] `0 \<le> real x`
  1715     by (rule mult_right_mono)
  1716   also have "\<dots> \<le> ?ln" using ln_bounds(1)[OF `0 \<le> real x` `real x < 1`] by auto
  1717   finally show "?lb \<le> ?ln" .
  1718 
  1719   have "?ln \<le> setsum ?s {0 ..< 2 * od + 1}" using ln_bounds(2)[OF `0 \<le> real x` `real x < 1`] by auto
  1720   also have "\<dots> \<le> ?ub" unfolding power_Suc2 mult_assoc[symmetric] real_of_float_mult setsum_left_distrib[symmetric] unfolding mult_commute[of "real x"] od
  1721     using horner_bounds(2)[where G="\<lambda> i k. Suc k" and F="\<lambda>x. x" and f="\<lambda>x. x" and lb="\<lambda>n i k x. lb_ln_horner prec n k x" and ub="\<lambda>n i k x. ub_ln_horner prec n k x" and j'=1 and n="2*od+1",
  1722       OF `0 \<le> real x` refl lb_ln_horner.simps ub_ln_horner.simps] `0 \<le> real x`
  1723     by (rule mult_right_mono)
  1724   finally show "?ln \<le> ?ub" .
  1725 qed
  1726 
  1727 lemma ln_add: assumes "0 < x" and "0 < y" shows "ln (x + y) = ln x + ln (1 + y / x)"
  1728 proof -
  1729   have "x \<noteq> 0" using assms by auto
  1730   have "x + y = x * (1 + y / x)" unfolding right_distrib times_divide_eq_right nonzero_mult_divide_cancel_left[OF `x \<noteq> 0`] by auto
  1731   moreover
  1732   have "0 < y / x" using assms divide_pos_pos by auto
  1733   hence "0 < 1 + y / x" by auto
  1734   ultimately show ?thesis using ln_mult assms by auto
  1735 qed
  1736 
  1737 subsection "Compute the logarithm of 2"
  1738 
  1739 definition ub_ln2 where "ub_ln2 prec = (let third = rapprox_rat (max prec 1) 1 3
  1740                                         in (Float 1 -1 * ub_ln_horner prec (get_odd prec) 1 (Float 1 -1)) +
  1741                                            (third * ub_ln_horner prec (get_odd prec) 1 third))"
  1742 definition lb_ln2 where "lb_ln2 prec = (let third = lapprox_rat prec 1 3
  1743                                         in (Float 1 -1 * lb_ln_horner prec (get_even prec) 1 (Float 1 -1)) +
  1744                                            (third * lb_ln_horner prec (get_even prec) 1 third))"
  1745 
  1746 lemma ub_ln2: "ln 2 \<le> ub_ln2 prec" (is "?ub_ln2")
  1747   and lb_ln2: "lb_ln2 prec \<le> ln 2" (is "?lb_ln2")
  1748 proof -
  1749   let ?uthird = "rapprox_rat (max prec 1) 1 3"
  1750   let ?lthird = "lapprox_rat prec 1 3"
  1751 
  1752   have ln2_sum: "ln 2 = ln (1/2 + 1) + ln (1 / 3 + 1)"
  1753     using ln_add[of "3 / 2" "1 / 2"] by auto
  1754   have lb3: "?lthird \<le> 1 / 3" using lapprox_rat[of prec 1 3] by auto
  1755   hence lb3_ub: "real ?lthird < 1" by auto
  1756   have lb3_lb: "0 \<le> real ?lthird" using lapprox_rat_bottom[of 1 3] by auto
  1757   have ub3: "1 / 3 \<le> ?uthird" using rapprox_rat[of 1 3] by auto
  1758   hence ub3_lb: "0 \<le> real ?uthird" by auto
  1759 
  1760   have lb2: "0 \<le> real (Float 1 -1)" and ub2: "real (Float 1 -1) < 1" unfolding Float_num by auto
  1761 
  1762   have "0 \<le> (1::int)" and "0 < (3::int)" by auto
  1763   have ub3_ub: "real ?uthird < 1" unfolding rapprox_rat.simps(2)[OF `0 \<le> 1` `0 < 3`]
  1764     by (rule rapprox_posrat_less1, auto)
  1765 
  1766   have third_gt0: "(0 :: real) < 1 / 3 + 1" by auto
  1767   have uthird_gt0: "0 < real ?uthird + 1" using ub3_lb by auto
  1768   have lthird_gt0: "0 < real ?lthird + 1" using lb3_lb by auto
  1769 
  1770   show ?ub_ln2 unfolding ub_ln2_def Let_def real_of_float_add ln2_sum Float_num(4)[symmetric]
  1771   proof (rule add_mono, fact ln_float_bounds(2)[OF lb2 ub2])
  1772     have "ln (1 / 3 + 1) \<le> ln (real ?uthird + 1)" unfolding ln_le_cancel_iff[OF third_gt0 uthird_gt0] using ub3 by auto
  1773     also have "\<dots> \<le> ?uthird * ub_ln_horner prec (get_odd prec) 1 ?uthird"
  1774       using ln_float_bounds(2)[OF ub3_lb ub3_ub] .
  1775     finally show "ln (1 / 3 + 1) \<le> ?uthird * ub_ln_horner prec (get_odd prec) 1 ?uthird" .
  1776   qed
  1777   show ?lb_ln2 unfolding lb_ln2_def Let_def real_of_float_add ln2_sum Float_num(4)[symmetric]
  1778   proof (rule add_mono, fact ln_float_bounds(1)[OF lb2 ub2])
  1779     have "?lthird * lb_ln_horner prec (get_even prec) 1 ?lthird \<le> ln (real ?lthird + 1)"
  1780       using ln_float_bounds(1)[OF lb3_lb lb3_ub] .
  1781     also have "\<dots> \<le> ln (1 / 3 + 1)" unfolding ln_le_cancel_iff[OF lthird_gt0 third_gt0] using lb3 by auto
  1782     finally show "?lthird * lb_ln_horner prec (get_even prec) 1 ?lthird \<le> ln (1 / 3 + 1)" .
  1783   qed
  1784 qed
  1785 
  1786 subsection "Compute the logarithm in the entire domain"
  1787 
  1788 function ub_ln :: "nat \<Rightarrow> float \<Rightarrow> float option" and lb_ln :: "nat \<Rightarrow> float \<Rightarrow> float option" where
  1789 "ub_ln prec x = (if x \<le> 0          then None
  1790             else if x < 1          then Some (- the (lb_ln prec (float_divl (max prec 1) 1 x)))
  1791             else let horner = \<lambda>x. x * ub_ln_horner prec (get_odd prec) 1 x in
  1792                  if x \<le> Float 3 -1 then Some (horner (x - 1))
  1793             else if x < Float 1 1  then Some (horner (Float 1 -1) + horner (x * rapprox_rat prec 2 3 - 1))
  1794                                    else let l = bitlen (mantissa x) - 1 in
  1795                                         Some (ub_ln2 prec * (Float (scale x + l) 0) + horner (Float (mantissa x) (- l) - 1)))" |
  1796 "lb_ln prec x = (if x \<le> 0          then None
  1797             else if x < 1          then Some (- the (ub_ln prec (float_divr prec 1 x)))
  1798             else let horner = \<lambda>x. x * lb_ln_horner prec (get_even prec) 1 x in
  1799                  if x \<le> Float 3 -1 then Some (horner (x - 1))
  1800             else if x < Float 1 1  then Some (horner (Float 1 -1) +
  1801                                               horner (max (x * lapprox_rat prec 2 3 - 1) 0))
  1802                                    else let l = bitlen (mantissa x) - 1 in
  1803                                         Some (lb_ln2 prec * (Float (scale x + l) 0) + horner (Float (mantissa x) (- l) - 1)))"
  1804 by pat_completeness auto
  1805 
  1806 termination proof (relation "measure (\<lambda> v. let (prec, x) = sum_case id id v in (if x < 1 then 1 else 0))", auto)
  1807   fix prec x assume "\<not> x \<le> 0" and "x < 1" and "float_divl (max prec (Suc 0)) 1 x < 1"
  1808   hence "0 < x" and "0 < max prec (Suc 0)" unfolding less_float_def le_float_def by auto
  1809   from float_divl_pos_less1_bound[OF `0 < x` `x < 1` `0 < max prec (Suc 0)`]
  1810   show False using `float_divl (max prec (Suc 0)) 1 x < 1` unfolding less_float_def le_float_def by auto
  1811 next
  1812   fix prec x assume "\<not> x \<le> 0" and "x < 1" and "float_divr prec 1 x < 1"
  1813   hence "0 < x" unfolding less_float_def le_float_def by auto
  1814   from float_divr_pos_less1_lower_bound[OF `0 < x` `x < 1`, of prec]
  1815   show False using `float_divr prec 1 x < 1` unfolding less_float_def le_float_def by auto
  1816 qed
  1817 
  1818 lemma ln_shifted_float: assumes "0 < m" shows "ln (Float m e) = ln 2 * (e + (bitlen m - 1)) + ln (Float m (- (bitlen m - 1)))"
  1819 proof -
  1820   let ?B = "2^nat (bitlen m - 1)"
  1821   have "0 < real m" and "\<And>X. (0 :: real) < 2^X" and "0 < (2 :: real)" and "m \<noteq> 0" using assms by auto
  1822   hence "0 \<le> bitlen m - 1" using bitlen_ge1[OF `m \<noteq> 0`] by auto
  1823   show ?thesis
  1824   proof (cases "0 \<le> e")
  1825     case True
  1826     show ?thesis unfolding normalized_float[OF `m \<noteq> 0`]
  1827       unfolding ln_div[OF `0 < real m` `0 < ?B`] real_of_int_add ln_realpow[OF `0 < 2`]
  1828       unfolding real_of_float_ge0_exp[OF True] ln_mult[OF `0 < real m` `0 < 2^nat e`]
  1829       ln_realpow[OF `0 < 2`] algebra_simps using `0 \<le> bitlen m - 1` True by auto
  1830   next
  1831     case False hence "0 < -e" by auto
  1832     hence pow_gt0: "(0::real) < 2^nat (-e)" by auto
  1833     hence inv_gt0: "(0::real) < inverse (2^nat (-e))" by auto
  1834     show ?thesis unfolding normalized_float[OF `m \<noteq> 0`]
  1835       unfolding ln_div[OF `0 < real m` `0 < ?B`] real_of_int_add ln_realpow[OF `0 < 2`]
  1836       unfolding real_of_float_nge0_exp[OF False] ln_mult[OF `0 < real m` inv_gt0] ln_inverse[OF pow_gt0]
  1837       ln_realpow[OF `0 < 2`] algebra_simps using `0 \<le> bitlen m - 1` False by auto
  1838   qed
  1839 qed
  1840 
  1841 lemma ub_ln_lb_ln_bounds': assumes "1 \<le> x"
  1842   shows "the (lb_ln prec x) \<le> ln x \<and> ln x \<le> the (ub_ln prec x)"
  1843   (is "?lb \<le> ?ln \<and> ?ln \<le> ?ub")
  1844 proof (cases "x < Float 1 1")
  1845   case True
  1846   hence "real (x - 1) < 1" and "real x < 2" unfolding less_float_def Float_num by auto
  1847   have "\<not> x \<le> 0" and "\<not> x < 1" using `1 \<le> x` unfolding less_float_def le_float_def by auto
  1848   hence "0 \<le> real (x - 1)" using `1 \<le> x` unfolding less_float_def Float_num by auto
  1849 
  1850   have [simp]: "(Float 3 -1) = 3 / 2" by (simp add: real_of_float_def pow2_def)
  1851 
  1852   show ?thesis
  1853   proof (cases "x \<le> Float 3 -1")
  1854     case True
  1855     show ?thesis unfolding lb_ln.simps unfolding ub_ln.simps Let_def
  1856       using ln_float_bounds[OF `0 \<le> real (x - 1)` `real (x - 1) < 1`, of prec] `\<not> x \<le> 0` `\<not> x < 1` True
  1857       by auto
  1858   next
  1859     case False hence *: "3 / 2 < x" by (auto simp add: le_float_def)
  1860 
  1861     with ln_add[of "3 / 2" "x - 3 / 2"]
  1862     have add: "ln x = ln (3 / 2) + ln (real x * 2 / 3)"
  1863       by (auto simp add: algebra_simps diff_divide_distrib)
  1864 
  1865     let "?ub_horner x" = "x * ub_ln_horner prec (get_odd prec) 1 x"
  1866     let "?lb_horner x" = "x * lb_ln_horner prec (get_even prec) 1 x"
  1867 
  1868     { have up: "real (rapprox_rat prec 2 3) \<le> 1"
  1869         by (rule rapprox_rat_le1) simp_all
  1870       have low: "2 / 3 \<le> rapprox_rat prec 2 3"
  1871         by (rule order_trans[OF _ rapprox_rat]) simp
  1872       from mult_less_le_imp_less[OF * low] *
  1873       have pos: "0 < real (x * rapprox_rat prec 2 3 - 1)" by auto
  1874 
  1875       have "ln (real x * 2/3)
  1876         \<le> ln (real (x * rapprox_rat prec 2 3 - 1) + 1)"
  1877       proof (rule ln_le_cancel_iff[symmetric, THEN iffD1])
  1878         show "real x * 2 / 3 \<le> real (x * rapprox_rat prec 2 3 - 1) + 1"
  1879           using * low by auto
  1880         show "0 < real x * 2 / 3" using * by simp
  1881         show "0 < real (x * rapprox_rat prec 2 3 - 1) + 1" using pos by auto
  1882       qed
  1883       also have "\<dots> \<le> ?ub_horner (x * rapprox_rat prec 2 3 - 1)"
  1884       proof (rule ln_float_bounds(2))
  1885         from mult_less_le_imp_less[OF `real x < 2` up] low *
  1886         show "real (x * rapprox_rat prec 2 3 - 1) < 1" by auto
  1887         show "0 \<le> real (x * rapprox_rat prec 2 3 - 1)" using pos by auto
  1888       qed
  1889       finally have "ln x
  1890         \<le> ?ub_horner (Float 1 -1)
  1891           + ?ub_horner (x * rapprox_rat prec 2 3 - 1)"
  1892         using ln_float_bounds(2)[of "Float 1 -1" prec prec] add by auto }
  1893     moreover
  1894     { let ?max = "max (x * lapprox_rat prec 2 3 - 1) 0"
  1895 
  1896       have up: "lapprox_rat prec 2 3 \<le> 2/3"
  1897         by (rule order_trans[OF lapprox_rat], simp)
  1898 
  1899       have low: "0 \<le> real (lapprox_rat prec 2 3)"
  1900         using lapprox_rat_bottom[of 2 3 prec] by simp
  1901 
  1902       have "?lb_horner ?max
  1903         \<le> ln (real ?max + 1)"
  1904       proof (rule ln_float_bounds(1))
  1905         from mult_less_le_imp_less[OF `real x < 2` up] * low
  1906         show "real ?max < 1" by (cases "real (lapprox_rat prec 2 3) = 0",
  1907           auto simp add: real_of_float_max)
  1908         show "0 \<le> real ?max" by (auto simp add: real_of_float_max)
  1909       qed
  1910       also have "\<dots> \<le> ln (real x * 2/3)"
  1911       proof (rule ln_le_cancel_iff[symmetric, THEN iffD1])
  1912         show "0 < real ?max + 1" by (auto simp add: real_of_float_max)
  1913         show "0 < real x * 2/3" using * by auto
  1914         show "real ?max + 1 \<le> real x * 2/3" using * up
  1915           by (cases "0 < real x * real (lapprox_posrat prec 2 3) - 1",
  1916               auto simp add: real_of_float_max min_max.sup_absorb1)
  1917       qed
  1918       finally have "?lb_horner (Float 1 -1) + ?lb_horner ?max
  1919         \<le> ln x"
  1920         using ln_float_bounds(1)[of "Float 1 -1" prec prec] add by auto }
  1921     ultimately
  1922     show ?thesis unfolding lb_ln.simps unfolding ub_ln.simps Let_def
  1923       using `\<not> x \<le> 0` `\<not> x < 1` True False by auto
  1924   qed
  1925 next
  1926   case False
  1927   hence "\<not> x \<le> 0" and "\<not> x < 1" "0 < x" "\<not> x \<le> Float 3 -1"
  1928     using `1 \<le> x` unfolding less_float_def le_float_def real_of_float_simp pow2_def
  1929     by auto
  1930   show ?thesis
  1931   proof (cases x)
  1932     case (Float m e)
  1933     let ?s = "Float (e + (bitlen m - 1)) 0"
  1934     let ?x = "Float m (- (bitlen m - 1))"
  1935 
  1936     have "0 < m" and "m \<noteq> 0" using float_pos_m_pos `0 < x` Float by auto
  1937 
  1938     {
  1939       have "lb_ln2 prec * ?s \<le> ln 2 * (e + (bitlen m - 1))" (is "?lb2 \<le> _")
  1940         unfolding real_of_float_mult real_of_float_ge0_exp[OF order_refl] nat_0 power_0 mult_1_right
  1941         using lb_ln2[of prec]
  1942       proof (rule mult_right_mono)
  1943         have "1 \<le> Float m e" using `1 \<le> x` Float unfolding le_float_def by auto
  1944         from float_gt1_scale[OF this]
  1945         show "0 \<le> real (e + (bitlen m - 1))" by auto
  1946       qed
  1947       moreover
  1948       from bitlen_div[OF `0 < m`, unfolded normalized_float[OF `m \<noteq> 0`, symmetric]]
  1949       have "0 \<le> real (?x - 1)" and "real (?x - 1) < 1" by auto
  1950       from ln_float_bounds(1)[OF this]
  1951       have "(?x - 1) * lb_ln_horner prec (get_even prec) 1 (?x - 1) \<le> ln ?x" (is "?lb_horner \<le> _") by auto
  1952       ultimately have "?lb2 + ?lb_horner \<le> ln x"
  1953         unfolding Float ln_shifted_float[OF `0 < m`, of e] by auto
  1954     }
  1955     moreover
  1956     {
  1957       from bitlen_div[OF `0 < m`, unfolded normalized_float[OF `m \<noteq> 0`, symmetric]]
  1958       have "0 \<le> real (?x - 1)" and "real (?x - 1) < 1" by auto
  1959       from ln_float_bounds(2)[OF this]
  1960       have "ln ?x \<le> (?x - 1) * ub_ln_horner prec (get_odd prec) 1 (?x - 1)" (is "_ \<le> ?ub_horner") by auto
  1961       moreover
  1962       have "ln 2 * (e + (bitlen m - 1)) \<le> ub_ln2 prec * ?s" (is "_ \<le> ?ub2")
  1963         unfolding real_of_float_mult real_of_float_ge0_exp[OF order_refl] nat_0 power_0 mult_1_right
  1964         using ub_ln2[of prec]
  1965       proof (rule mult_right_mono)
  1966         have "1 \<le> Float m e" using `1 \<le> x` Float unfolding le_float_def by auto
  1967         from float_gt1_scale[OF this]
  1968         show "0 \<le> real (e + (bitlen m - 1))" by auto
  1969       qed
  1970       ultimately have "ln x \<le> ?ub2 + ?ub_horner"
  1971         unfolding Float ln_shifted_float[OF `0 < m`, of e] by auto
  1972     }
  1973     ultimately show ?thesis unfolding lb_ln.simps unfolding ub_ln.simps
  1974       unfolding if_not_P[OF `\<not> x \<le> 0`] if_not_P[OF `\<not> x < 1`] if_not_P[OF False] if_not_P[OF `\<not> x \<le> Float 3 -1`] Let_def
  1975       unfolding scale.simps[of m e, unfolded Float[symmetric]] mantissa.simps[of m e, unfolded Float[symmetric]] real_of_float_add
  1976       by auto
  1977   qed
  1978 qed
  1979 
  1980 lemma ub_ln_lb_ln_bounds: assumes "0 < x"
  1981   shows "the (lb_ln prec x) \<le> ln x \<and> ln x \<le> the (ub_ln prec x)"
  1982   (is "?lb \<le> ?ln \<and> ?ln \<le> ?ub")
  1983 proof (cases "x < 1")
  1984   case False hence "1 \<le> x" unfolding less_float_def le_float_def by auto
  1985   show ?thesis using ub_ln_lb_ln_bounds'[OF `1 \<le> x`] .
  1986 next
  1987   case True have "\<not> x \<le> 0" using `0 < x` unfolding less_float_def le_float_def by auto
  1988 
  1989   have "0 < real x" and "real x \<noteq> 0" using `0 < x` unfolding less_float_def by auto
  1990   hence A: "0 < 1 / real x" by auto
  1991 
  1992   {
  1993     let ?divl = "float_divl (max prec 1) 1 x"
  1994     have A': "1 \<le> ?divl" using float_divl_pos_less1_bound[OF `0 < x` `x < 1`] unfolding le_float_def less_float_def by auto
  1995     hence B: "0 < real ?divl" unfolding le_float_def by auto
  1996 
  1997     have "ln ?divl \<le> ln (1 / x)" unfolding ln_le_cancel_iff[OF B A] using float_divl[of _ 1 x] by auto
  1998     hence "ln x \<le> - ln ?divl" unfolding nonzero_inverse_eq_divide[OF `real x \<noteq> 0`, symmetric] ln_inverse[OF `0 < real x`] by auto
  1999     from this ub_ln_lb_ln_bounds'[OF A', THEN conjunct1, THEN le_imp_neg_le]
  2000     have "?ln \<le> - the (lb_ln prec ?divl)" unfolding real_of_float_minus by (rule order_trans)
  2001   } moreover
  2002   {
  2003     let ?divr = "float_divr prec 1 x"
  2004     have A': "1 \<le> ?divr" using float_divr_pos_less1_lower_bound[OF `0 < x` `x < 1`] unfolding le_float_def less_float_def by auto
  2005     hence B: "0 < real ?divr" unfolding le_float_def by auto
  2006 
  2007     have "ln (1 / x) \<le> ln ?divr" unfolding ln_le_cancel_iff[OF A B] using float_divr[of 1 x] by auto
  2008     hence "- ln ?divr \<le> ln x" unfolding nonzero_inverse_eq_divide[OF `real x \<noteq> 0`, symmetric] ln_inverse[OF `0 < real x`] by auto
  2009     from ub_ln_lb_ln_bounds'[OF A', THEN conjunct2, THEN le_imp_neg_le] this
  2010     have "- the (ub_ln prec ?divr) \<le> ?ln" unfolding real_of_float_minus by (rule order_trans)
  2011   }
  2012   ultimately show ?thesis unfolding lb_ln.simps[where x=x]  ub_ln.simps[where x=x]
  2013     unfolding if_not_P[OF `\<not> x \<le> 0`] if_P[OF True] by auto
  2014 qed
  2015 
  2016 lemma lb_ln: assumes "Some y = lb_ln prec x"
  2017   shows "y \<le> ln x" and "0 < real x"
  2018 proof -
  2019   have "0 < x"
  2020   proof (rule ccontr)
  2021     assume "\<not> 0 < x" hence "x \<le> 0" unfolding le_float_def less_float_def by auto
  2022     thus False using assms by auto
  2023   qed
  2024   thus "0 < real x" unfolding less_float_def by auto
  2025   have "the (lb_ln prec x) \<le> ln x" using ub_ln_lb_ln_bounds[OF `0 < x`] ..
  2026   thus "y \<le> ln x" unfolding assms[symmetric] by auto
  2027 qed
  2028 
  2029 lemma ub_ln: assumes "Some y = ub_ln prec x"
  2030   shows "ln x \<le> y" and "0 < real x"
  2031 proof -
  2032   have "0 < x"
  2033   proof (rule ccontr)
  2034     assume "\<not> 0 < x" hence "x \<le> 0" unfolding le_float_def less_float_def by auto
  2035     thus False using assms by auto
  2036   qed
  2037   thus "0 < real x" unfolding less_float_def by auto
  2038   have "ln x \<le> the (ub_ln prec x)" using ub_ln_lb_ln_bounds[OF `0 < x`] ..
  2039   thus "ln x \<le> y" unfolding assms[symmetric] by auto
  2040 qed
  2041 
  2042 lemma bnds_ln: "\<forall> (x::real) lx ux. (Some l, Some u) = (lb_ln prec lx, ub_ln prec ux) \<and> x \<in> {lx .. ux} \<longrightarrow> l \<le> ln x \<and> ln x \<le> u"
  2043 proof (rule allI, rule allI, rule allI, rule impI)
  2044   fix x::real and lx ux
  2045   assume "(Some l, Some u) = (lb_ln prec lx, ub_ln prec ux) \<and> x \<in> {lx .. ux}"
  2046   hence l: "Some l = lb_ln prec lx " and u: "Some u = ub_ln prec ux" and x: "x \<in> {lx .. ux}" by auto
  2047 
  2048   have "ln ux \<le> u" and "0 < real ux" using ub_ln u by auto
  2049   have "l \<le> ln lx" and "0 < real lx" and "0 < x" using lb_ln[OF l] x by auto
  2050 
  2051   from ln_le_cancel_iff[OF `0 < real lx` `0 < x`] `l \<le> ln lx`
  2052   have "l \<le> ln x" using x unfolding atLeastAtMost_iff by auto
  2053   moreover
  2054   from ln_le_cancel_iff[OF `0 < x` `0 < real ux`] `ln ux \<le> real u`
  2055   have "ln x \<le> u" using x unfolding atLeastAtMost_iff by auto
  2056   ultimately show "l \<le> ln x \<and> ln x \<le> u" ..
  2057 qed
  2058 
  2059 section "Implement floatarith"
  2060 
  2061 subsection "Define syntax and semantics"
  2062 
  2063 datatype floatarith
  2064   = Add floatarith floatarith
  2065   | Minus floatarith
  2066   | Mult floatarith floatarith
  2067   | Inverse floatarith
  2068   | Cos floatarith
  2069   | Arctan floatarith
  2070   | Abs floatarith
  2071   | Max floatarith floatarith
  2072   | Min floatarith floatarith
  2073   | Pi
  2074   | Sqrt floatarith
  2075   | Exp floatarith
  2076   | Ln floatarith
  2077   | Power floatarith nat
  2078   | Var nat
  2079   | Num float
  2080 
  2081 fun interpret_floatarith :: "floatarith \<Rightarrow> real list \<Rightarrow> real" where
  2082 "interpret_floatarith (Add a b) vs   = (interpret_floatarith a vs) + (interpret_floatarith b vs)" |
  2083 "interpret_floatarith (Minus a) vs    = - (interpret_floatarith a vs)" |
  2084 "interpret_floatarith (Mult a b) vs   = (interpret_floatarith a vs) * (interpret_floatarith b vs)" |
  2085 "interpret_floatarith (Inverse a) vs  = inverse (interpret_floatarith a vs)" |
  2086 "interpret_floatarith (Cos a) vs      = cos (interpret_floatarith a vs)" |
  2087 "interpret_floatarith (Arctan a) vs   = arctan (interpret_floatarith a vs)" |
  2088 "interpret_floatarith (Min a b) vs    = min (interpret_floatarith a vs) (interpret_floatarith b vs)" |
  2089 "interpret_floatarith (Max a b) vs    = max (interpret_floatarith a vs) (interpret_floatarith b vs)" |
  2090 "interpret_floatarith (Abs a) vs      = abs (interpret_floatarith a vs)" |
  2091 "interpret_floatarith Pi vs           = pi" |
  2092 "interpret_floatarith (Sqrt a) vs     = sqrt (interpret_floatarith a vs)" |
  2093 "interpret_floatarith (Exp a) vs      = exp (interpret_floatarith a vs)" |
  2094 "interpret_floatarith (Ln a) vs       = ln (interpret_floatarith a vs)" |
  2095 "interpret_floatarith (Power a n) vs  = (interpret_floatarith a vs)^n" |
  2096 "interpret_floatarith (Num f) vs      = f" |
  2097 "interpret_floatarith (Var n) vs     = vs ! n"
  2098 
  2099 lemma interpret_floatarith_divide: "interpret_floatarith (Mult a (Inverse b)) vs = (interpret_floatarith a vs) / (interpret_floatarith b vs)"
  2100   unfolding divide_inverse interpret_floatarith.simps ..
  2101 
  2102 lemma interpret_floatarith_diff: "interpret_floatarith (Add a (Minus b)) vs = (interpret_floatarith a vs) - (interpret_floatarith b vs)"
  2103   unfolding diff_minus interpret_floatarith.simps ..
  2104 
  2105 lemma interpret_floatarith_sin: "interpret_floatarith (Cos (Add (Mult Pi (Num (Float 1 -1))) (Minus a))) vs =
  2106   sin (interpret_floatarith a vs)"
  2107   unfolding sin_cos_eq interpret_floatarith.simps
  2108             interpret_floatarith_divide interpret_floatarith_diff diff_minus
  2109   by auto
  2110 
  2111 lemma interpret_floatarith_tan:
  2112   "interpret_floatarith (Mult (Cos (Add (Mult Pi (Num (Float 1 -1))) (Minus a))) (Inverse (Cos a))) vs =
  2113    tan (interpret_floatarith a vs)"
  2114   unfolding interpret_floatarith.simps(3,4) interpret_floatarith_sin tan_def divide_inverse
  2115   by auto
  2116 
  2117 lemma interpret_floatarith_powr: "interpret_floatarith (Exp (Mult b (Ln a))) vs = (interpret_floatarith a vs) powr (interpret_floatarith b vs)"
  2118   unfolding powr_def interpret_floatarith.simps ..
  2119 
  2120 lemma interpret_floatarith_log: "interpret_floatarith ((Mult (Ln x) (Inverse (Ln b)))) vs = log (interpret_floatarith b vs) (interpret_floatarith x vs)"
  2121   unfolding log_def interpret_floatarith.simps divide_inverse ..
  2122 
  2123 lemma interpret_floatarith_num:
  2124   shows "interpret_floatarith (Num (Float 0 0)) vs = 0"
  2125   and "interpret_floatarith (Num (Float 1 0)) vs = 1"
  2126   and "interpret_floatarith (Num (Float (number_of a) 0)) vs = number_of a" by auto
  2127 
  2128 subsection "Implement approximation function"
  2129 
  2130 fun lift_bin' :: "(float * float) option \<Rightarrow> (float * float) option \<Rightarrow> (float \<Rightarrow> float \<Rightarrow> float \<Rightarrow> float \<Rightarrow> (float * float)) \<Rightarrow> (float * float) option" where
  2131 "lift_bin' (Some (l1, u1)) (Some (l2, u2)) f = Some (f l1 u1 l2 u2)" |
  2132 "lift_bin' a b f = None"
  2133 
  2134 fun lift_un :: "(float * float) option \<Rightarrow> (float \<Rightarrow> float \<Rightarrow> ((float option) * (float option))) \<Rightarrow> (float * float) option" where
  2135 "lift_un (Some (l1, u1)) f = (case (f l1 u1) of (Some l, Some u) \<Rightarrow> Some (l, u)
  2136                                              | t \<Rightarrow> None)" |
  2137 "lift_un b f = None"
  2138 
  2139 fun lift_un' :: "(float * float) option \<Rightarrow> (float \<Rightarrow> float \<Rightarrow> (float * float)) \<Rightarrow> (float * float) option" where
  2140 "lift_un' (Some (l1, u1)) f = Some (f l1 u1)" |
  2141 "lift_un' b f = None"
  2142 
  2143 definition
  2144 "bounded_by xs vs \<longleftrightarrow>
  2145   (\<forall> i < length vs. case vs ! i of None \<Rightarrow> True
  2146          | Some (l, u) \<Rightarrow> xs ! i \<in> { real l .. real u })"
  2147 
  2148 lemma bounded_byE:
  2149   assumes "bounded_by xs vs"
  2150   shows "\<And> i. i < length vs \<Longrightarrow> case vs ! i of None \<Rightarrow> True
  2151          | Some (l, u) \<Rightarrow> xs ! i \<in> { real l .. real u }"
  2152   using assms bounded_by_def by blast
  2153 
  2154 lemma bounded_by_update:
  2155   assumes "bounded_by xs vs"
  2156   and bnd: "xs ! i \<in> { real l .. real u }"
  2157   shows "bounded_by xs (vs[i := Some (l,u)])"
  2158 proof -
  2159 { fix j
  2160   let ?vs = "vs[i := Some (l,u)]"
  2161   assume "j < length ?vs" hence [simp]: "j < length vs" by simp
  2162   have "case ?vs ! j of None \<Rightarrow> True | Some (l, u) \<Rightarrow> xs ! j \<in> { real l .. real u }"
  2163   proof (cases "?vs ! j")
  2164     case (Some b)
  2165     thus ?thesis
  2166     proof (cases "i = j")
  2167       case True
  2168       thus ?thesis using `?vs ! j = Some b` and bnd by auto
  2169     next
  2170       case False
  2171       thus ?thesis using `bounded_by xs vs` unfolding bounded_by_def by auto
  2172     qed
  2173   qed auto }
  2174   thus ?thesis unfolding bounded_by_def by auto
  2175 qed
  2176 
  2177 lemma bounded_by_None:
  2178   shows "bounded_by xs (replicate (length xs) None)"
  2179   unfolding bounded_by_def by auto
  2180 
  2181 fun approx approx' :: "nat \<Rightarrow> floatarith \<Rightarrow> (float * float) option list \<Rightarrow> (float * float) option" where
  2182 "approx' prec a bs          = (case (approx prec a bs) of Some (l, u) \<Rightarrow> Some (round_down prec l, round_up prec u) | None \<Rightarrow> None)" |
  2183 "approx prec (Add a b) bs   = lift_bin' (approx' prec a bs) (approx' prec b bs) (\<lambda> l1 u1 l2 u2. (l1 + l2, u1 + u2))" |
  2184 "approx prec (Minus a) bs   = lift_un' (approx' prec a bs) (\<lambda> l u. (-u, -l))" |
  2185 "approx prec (Mult a b) bs  = lift_bin' (approx' prec a bs) (approx' prec b bs)
  2186                                     (\<lambda> a1 a2 b1 b2. (float_nprt a1 * float_pprt b2 + float_nprt a2 * float_nprt b2 + float_pprt a1 * float_pprt b1 + float_pprt a2 * float_nprt b1,
  2187                                                      float_pprt a2 * float_pprt b2 + float_pprt a1 * float_nprt b2 + float_nprt a2 * float_pprt b1 + float_nprt a1 * float_nprt b1))" |
  2188 "approx prec (Inverse a) bs = lift_un (approx' prec a bs) (\<lambda> l u. if (0 < l \<or> u < 0) then (Some (float_divl prec 1 u), Some (float_divr prec 1 l)) else (None, None))" |
  2189 "approx prec (Cos a) bs     = lift_un' (approx' prec a bs) (bnds_cos prec)" |
  2190 "approx prec Pi bs          = Some (lb_pi prec, ub_pi prec)" |
  2191 "approx prec (Min a b) bs   = lift_bin' (approx' prec a bs) (approx' prec b bs) (\<lambda> l1 u1 l2 u2. (min l1 l2, min u1 u2))" |
  2192 "approx prec (Max a b) bs   = lift_bin' (approx' prec a bs) (approx' prec b bs) (\<lambda> l1 u1 l2 u2. (max l1 l2, max u1 u2))" |
  2193 "approx prec (Abs a) bs     = lift_un' (approx' prec a bs) (\<lambda>l u. (if l < 0 \<and> 0 < u then 0 else min \<bar>l\<bar> \<bar>u\<bar>, max \<bar>l\<bar> \<bar>u\<bar>))" |
  2194 "approx prec (Arctan a) bs  = lift_un' (approx' prec a bs) (\<lambda> l u. (lb_arctan prec l, ub_arctan prec u))" |
  2195 "approx prec (Sqrt a) bs    = lift_un' (approx' prec a bs) (\<lambda> l u. (lb_sqrt prec l, ub_sqrt prec u))" |
  2196 "approx prec (Exp a) bs     = lift_un' (approx' prec a bs) (\<lambda> l u. (lb_exp prec l, ub_exp prec u))" |
  2197 "approx prec (Ln a) bs      = lift_un (approx' prec a bs) (\<lambda> l u. (lb_ln prec l, ub_ln prec u))" |
  2198 "approx prec (Power a n) bs = lift_un' (approx' prec a bs) (float_power_bnds n)" |
  2199 "approx prec (Num f) bs     = Some (f, f)" |
  2200 "approx prec (Var i) bs    = (if i < length bs then bs ! i else None)"
  2201 
  2202 lemma lift_bin'_ex:
  2203   assumes lift_bin'_Some: "Some (l, u) = lift_bin' a b f"
  2204   shows "\<exists> l1 u1 l2 u2. Some (l1, u1) = a \<and> Some (l2, u2) = b"
  2205 proof (cases a)
  2206   case None hence "None = lift_bin' a b f" unfolding None lift_bin'.simps ..
  2207   thus ?thesis using lift_bin'_Some by auto
  2208 next
  2209   case (Some a')
  2210   show ?thesis
  2211   proof (cases b)
  2212     case None hence "None = lift_bin' a b f" unfolding None lift_bin'.simps ..
  2213     thus ?thesis using lift_bin'_Some by auto
  2214   next
  2215     case (Some b')
  2216     obtain la ua where a': "a' = (la, ua)" by (cases a', auto)
  2217     obtain lb ub where b': "b' = (lb, ub)" by (cases b', auto)
  2218     thus ?thesis unfolding `a = Some a'` `b = Some b'` a' b' by auto
  2219   qed
  2220 qed
  2221 
  2222 lemma lift_bin'_f:
  2223   assumes lift_bin'_Some: "Some (l, u) = lift_bin' (g a) (g b) f"
  2224   and Pa: "\<And>l u. Some (l, u) = g a \<Longrightarrow> P l u a" and Pb: "\<And>l u. Some (l, u) = g b \<Longrightarrow> P l u b"
  2225   shows "\<exists> l1 u1 l2 u2. P l1 u1 a \<and> P l2 u2 b \<and> l = fst (f l1 u1 l2 u2) \<and> u = snd (f l1 u1 l2 u2)"
  2226 proof -
  2227   obtain l1 u1 l2 u2
  2228     where Sa: "Some (l1, u1) = g a" and Sb: "Some (l2, u2) = g b" using lift_bin'_ex[OF assms(1)] by auto
  2229   have lu: "(l, u) = f l1 u1 l2 u2" using lift_bin'_Some[unfolded Sa[symmetric] Sb[symmetric] lift_bin'.simps] by auto
  2230   have "l = fst (f l1 u1 l2 u2)" and "u = snd (f l1 u1 l2 u2)" unfolding lu[symmetric] by auto
  2231   thus ?thesis using Pa[OF Sa] Pb[OF Sb] by auto
  2232 qed
  2233 
  2234 lemma approx_approx':
  2235   assumes Pa: "\<And>l u. Some (l, u) = approx prec a vs \<Longrightarrow> l \<le> interpret_floatarith a xs \<and> interpret_floatarith a xs \<le> u"
  2236   and approx': "Some (l, u) = approx' prec a vs"
  2237   shows "l \<le> interpret_floatarith a xs \<and> interpret_floatarith a xs \<le> u"
  2238 proof -
  2239   obtain l' u' where S: "Some (l', u') = approx prec a vs"
  2240     using approx' unfolding approx'.simps by (cases "approx prec a vs", auto)
  2241   have l': "l = round_down prec l'" and u': "u = round_up prec u'"
  2242     using approx' unfolding approx'.simps S[symmetric] by auto
  2243   show ?thesis unfolding l' u'
  2244     using order_trans[OF Pa[OF S, THEN conjunct2] round_up[of u']]
  2245     using order_trans[OF round_down[of _ l'] Pa[OF S, THEN conjunct1]] by auto
  2246 qed
  2247 
  2248 lemma lift_bin':
  2249   assumes lift_bin'_Some: "Some (l, u) = lift_bin' (approx' prec a bs) (approx' prec b bs) f"
  2250   and Pa: "\<And>l u. Some (l, u) = approx prec a bs \<Longrightarrow> l \<le> interpret_floatarith a xs \<and> interpret_floatarith a xs \<le> u" (is "\<And>l u. _ = ?g a \<Longrightarrow> ?P l u a")
  2251   and Pb: "\<And>l u. Some (l, u) = approx prec b bs \<Longrightarrow> l \<le> interpret_floatarith b xs \<and> interpret_floatarith b xs \<le> u"
  2252   shows "\<exists> l1 u1 l2 u2. (l1 \<le> interpret_floatarith a xs \<and> interpret_floatarith a xs \<le> u1) \<and>
  2253                         (l2 \<le> interpret_floatarith b xs \<and> interpret_floatarith b xs \<le> u2) \<and>
  2254                         l = fst (f l1 u1 l2 u2) \<and> u = snd (f l1 u1 l2 u2)"
  2255 proof -
  2256   { fix l u assume "Some (l, u) = approx' prec a bs"
  2257     with approx_approx'[of prec a bs, OF _ this] Pa
  2258     have "l \<le> interpret_floatarith a xs \<and> interpret_floatarith a xs \<le> u" by auto } note Pa = this
  2259   { fix l u assume "Some (l, u) = approx' prec b bs"
  2260     with approx_approx'[of prec b bs, OF _ this] Pb
  2261     have "l \<le> interpret_floatarith b xs \<and> interpret_floatarith b xs \<le> u" by auto } note Pb = this
  2262 
  2263   from lift_bin'_f[where g="\<lambda>a. approx' prec a bs" and P = ?P, OF lift_bin'_Some, OF Pa Pb]
  2264   show ?thesis by auto
  2265 qed
  2266 
  2267 lemma lift_un'_ex:
  2268   assumes lift_un'_Some: "Some (l, u) = lift_un' a f"
  2269   shows "\<exists> l u. Some (l, u) = a"
  2270 proof (cases a)
  2271   case None hence "None = lift_un' a f" unfolding None lift_un'.simps ..
  2272   thus ?thesis using lift_un'_Some by auto
  2273 next
  2274   case (Some a')
  2275   obtain la ua where a': "a' = (la, ua)" by (cases a', auto)
  2276   thus ?thesis unfolding `a = Some a'` a' by auto
  2277 qed
  2278 
  2279 lemma lift_un'_f:
  2280   assumes lift_un'_Some: "Some (l, u) = lift_un' (g a) f"
  2281   and Pa: "\<And>l u. Some (l, u) = g a \<Longrightarrow> P l u a"
  2282   shows "\<exists> l1 u1. P l1 u1 a \<and> l = fst (f l1 u1) \<and> u = snd (f l1 u1)"
  2283 proof -
  2284   obtain l1 u1 where Sa: "Some (l1, u1) = g a" using lift_un'_ex[OF assms(1)] by auto
  2285   have lu: "(l, u) = f l1 u1" using lift_un'_Some[unfolded Sa[symmetric] lift_un'.simps] by auto
  2286   have "l = fst (f l1 u1)" and "u = snd (f l1 u1)" unfolding lu[symmetric] by auto
  2287   thus ?thesis using Pa[OF Sa] by auto
  2288 qed
  2289 
  2290 lemma lift_un':
  2291   assumes lift_un'_Some: "Some (l, u) = lift_un' (approx' prec a bs) f"
  2292   and Pa: "\<And>l u. Some (l, u) = approx prec a bs \<Longrightarrow> l \<le> interpret_floatarith a xs \<and> interpret_floatarith a xs \<le> u" (is "\<And>l u. _ = ?g a \<Longrightarrow> ?P l u a")
  2293   shows "\<exists> l1 u1. (l1 \<le> interpret_floatarith a xs \<and> interpret_floatarith a xs \<le> u1) \<and>
  2294                         l = fst (f l1 u1) \<and> u = snd (f l1 u1)"
  2295 proof -
  2296   { fix l u assume "Some (l, u) = approx' prec a bs"
  2297     with approx_approx'[of prec a bs, OF _ this] Pa
  2298     have "l \<le> interpret_floatarith a xs \<and> interpret_floatarith a xs \<le> u" by auto } note Pa = this
  2299   from lift_un'_f[where g="\<lambda>a. approx' prec a bs" and P = ?P, OF lift_un'_Some, OF Pa]
  2300   show ?thesis by auto
  2301 qed
  2302 
  2303 lemma lift_un'_bnds:
  2304   assumes bnds: "\<forall> (x::real) lx ux. (l, u) = f lx ux \<and> x \<in> { lx .. ux } \<longrightarrow> l \<le> f' x \<and> f' x \<le> u"
  2305   and lift_un'_Some: "Some (l, u) = lift_un' (approx' prec a bs) f"
  2306   and Pa: "\<And>l u. Some (l, u) = approx prec a bs \<Longrightarrow> l \<le> interpret_floatarith a xs \<and> interpret_floatarith a xs \<le> u"
  2307   shows "real l \<le> f' (interpret_floatarith a xs) \<and> f' (interpret_floatarith a xs) \<le> real u"
  2308 proof -
  2309   from lift_un'[OF lift_un'_Some Pa]
  2310   obtain l1 u1 where "l1 \<le> interpret_floatarith a xs" and "interpret_floatarith a xs \<le> u1" and "l = fst (f l1 u1)" and "u = snd (f l1 u1)" by blast
  2311   hence "(l, u) = f l1 u1" and "interpret_floatarith a xs \<in> {l1 .. u1}" by auto
  2312   thus ?thesis using bnds by auto
  2313 qed
  2314 
  2315 lemma lift_un_ex:
  2316   assumes lift_un_Some: "Some (l, u) = lift_un a f"
  2317   shows "\<exists> l u. Some (l, u) = a"
  2318 proof (cases a)
  2319   case None hence "None = lift_un a f" unfolding None lift_un.simps ..
  2320   thus ?thesis using lift_un_Some by auto
  2321 next
  2322   case (Some a')
  2323   obtain la ua where a': "a' = (la, ua)" by (cases a', auto)
  2324   thus ?thesis unfolding `a = Some a'` a' by auto
  2325 qed
  2326 
  2327 lemma lift_un_f:
  2328   assumes lift_un_Some: "Some (l, u) = lift_un (g a) f"
  2329   and Pa: "\<And>l u. Some (l, u) = g a \<Longrightarrow> P l u a"
  2330   shows "\<exists> l1 u1. P l1 u1 a \<and> Some l = fst (f l1 u1) \<and> Some u = snd (f l1 u1)"
  2331 proof -
  2332   obtain l1 u1 where Sa: "Some (l1, u1) = g a" using lift_un_ex[OF assms(1)] by auto
  2333   have "fst (f l1 u1) \<noteq> None \<and> snd (f l1 u1) \<noteq> None"
  2334   proof (rule ccontr)
  2335     assume "\<not> (fst (f l1 u1) \<noteq> None \<and> snd (f l1 u1) \<noteq> None)"
  2336     hence or: "fst (f l1 u1) = None \<or> snd (f l1 u1) = None" by auto
  2337     hence "lift_un (g a) f = None"
  2338     proof (cases "fst (f l1 u1) = None")
  2339       case True
  2340       then obtain b where b: "f l1 u1 = (None, b)" by (cases "f l1 u1", auto)
  2341       thus ?thesis unfolding Sa[symmetric] lift_un.simps b by auto
  2342     next
  2343       case False hence "snd (f l1 u1) = None" using or by auto
  2344       with False obtain b where b: "f l1 u1 = (Some b, None)" by (cases "f l1 u1", auto)
  2345       thus ?thesis unfolding Sa[symmetric] lift_un.simps b by auto
  2346     qed
  2347     thus False using lift_un_Some by auto
  2348   qed
  2349   then obtain a' b' where f: "f l1 u1 = (Some a', Some b')" by (cases "f l1 u1", auto)
  2350   from lift_un_Some[unfolded Sa[symmetric] lift_un.simps f]
  2351   have "Some l = fst (f l1 u1)" and "Some u = snd (f l1 u1)" unfolding f by auto
  2352   thus ?thesis unfolding Sa[symmetric] lift_un.simps using Pa[OF Sa] by auto
  2353 qed
  2354 
  2355 lemma lift_un:
  2356   assumes lift_un_Some: "Some (l, u) = lift_un (approx' prec a bs) f"
  2357   and Pa: "\<And>l u. Some (l, u) = approx prec a bs \<Longrightarrow> l \<le> interpret_floatarith a xs \<and> interpret_floatarith a xs \<le> u" (is "\<And>l u. _ = ?g a \<Longrightarrow> ?P l u a")
  2358   shows "\<exists> l1 u1. (l1 \<le> interpret_floatarith a xs \<and> interpret_floatarith a xs \<le> u1) \<and>
  2359                   Some l = fst (f l1 u1) \<and> Some u = snd (f l1 u1)"
  2360 proof -
  2361   { fix l u assume "Some (l, u) = approx' prec a bs"
  2362     with approx_approx'[of prec a bs, OF _ this] Pa
  2363     have "l \<le> interpret_floatarith a xs \<and> interpret_floatarith a xs \<le> u" by auto } note Pa = this
  2364   from lift_un_f[where g="\<lambda>a. approx' prec a bs" and P = ?P, OF lift_un_Some, OF Pa]
  2365   show ?thesis by auto
  2366 qed
  2367 
  2368 lemma lift_un_bnds:
  2369   assumes bnds: "\<forall> (x::real) lx ux. (Some l, Some u) = f lx ux \<and> x \<in> { lx .. ux } \<longrightarrow> l \<le> f' x \<and> f' x \<le> u"
  2370   and lift_un_Some: "Some (l, u) = lift_un (approx' prec a bs) f"
  2371   and Pa: "\<And>l u. Some (l, u) = approx prec a bs \<Longrightarrow> l \<le> interpret_floatarith a xs \<and> interpret_floatarith a xs \<le> u"
  2372   shows "real l \<le> f' (interpret_floatarith a xs) \<and> f' (interpret_floatarith a xs) \<le> real u"
  2373 proof -
  2374   from lift_un[OF lift_un_Some Pa]
  2375   obtain l1 u1 where "l1 \<le> interpret_floatarith a xs" and "interpret_floatarith a xs \<le> u1" and "Some l = fst (f l1 u1)" and "Some u = snd (f l1 u1)" by blast
  2376   hence "(Some l, Some u) = f l1 u1" and "interpret_floatarith a xs \<in> {l1 .. u1}" by auto
  2377   thus ?thesis using bnds by auto
  2378 qed
  2379 
  2380 lemma approx:
  2381   assumes "bounded_by xs vs"
  2382   and "Some (l, u) = approx prec arith vs" (is "_ = ?g arith")
  2383   shows "l \<le> interpret_floatarith arith xs \<and> interpret_floatarith arith xs \<le> u" (is "?P l u arith")
  2384   using `Some (l, u) = approx prec arith vs`
  2385 proof (induct arith arbitrary: l u x)
  2386   case (Add a b)
  2387   from lift_bin'[OF Add.prems[unfolded approx.simps]] Add.hyps
  2388   obtain l1 u1 l2 u2 where "l = l1 + l2" and "u = u1 + u2"
  2389     "l1 \<le> interpret_floatarith a xs" and "interpret_floatarith a xs \<le> u1"
  2390     "l2 \<le> interpret_floatarith b xs" and "interpret_floatarith b xs \<le> u2" unfolding fst_conv snd_conv by blast
  2391   thus ?case unfolding interpret_floatarith.simps by auto
  2392 next
  2393   case (Minus a)
  2394   from lift_un'[OF Minus.prems[unfolded approx.simps]] Minus.hyps
  2395   obtain l1 u1 where "l = -u1" and "u = -l1"
  2396     "l1 \<le> interpret_floatarith a xs" and "interpret_floatarith a xs \<le> u1" unfolding fst_conv snd_conv by blast
  2397   thus ?case unfolding interpret_floatarith.simps using real_of_float_minus by auto
  2398 next
  2399   case (Mult a b)
  2400   from lift_bin'[OF Mult.prems[unfolded approx.simps]] Mult.hyps
  2401   obtain l1 u1 l2 u2
  2402     where l: "l = float_nprt l1 * float_pprt u2 + float_nprt u1 * float_nprt u2 + float_pprt l1 * float_pprt l2 + float_pprt u1 * float_nprt l2"
  2403     and u: "u = float_pprt u1 * float_pprt u2 + float_pprt l1 * float_nprt u2 + float_nprt u1 * float_pprt l2 + float_nprt l1 * float_nprt l2"
  2404     and "l1 \<le> interpret_floatarith a xs" and "interpret_floatarith a xs \<le> u1"
  2405     and "l2 \<le> interpret_floatarith b xs" and "interpret_floatarith b xs \<le> u2" unfolding fst_conv snd_conv by blast
  2406   thus ?case unfolding interpret_floatarith.simps l u real_of_float_add real_of_float_mult real_of_float_nprt real_of_float_pprt
  2407     using mult_le_prts mult_ge_prts by auto
  2408 next
  2409   case (Inverse a)
  2410   from lift_un[OF Inverse.prems[unfolded approx.simps], unfolded if_distrib[of fst] if_distrib[of snd] fst_conv snd_conv] Inverse.hyps
  2411   obtain l1 u1 where l': "Some l = (if 0 < l1 \<or> u1 < 0 then Some (float_divl prec 1 u1) else None)"
  2412     and u': "Some u = (if 0 < l1 \<or> u1 < 0 then Some (float_divr prec 1 l1) else None)"
  2413     and l1: "l1 \<le> interpret_floatarith a xs" and u1: "interpret_floatarith a xs \<le> u1" by blast
  2414   have either: "0 < l1 \<or> u1 < 0" proof (rule ccontr) assume P: "\<not> (0 < l1 \<or> u1 < 0)" show False using l' unfolding if_not_P[OF P] by auto qed
  2415   moreover have l1_le_u1: "real l1 \<le> real u1" using l1 u1 by auto
  2416   ultimately have "real l1 \<noteq> 0" and "real u1 \<noteq> 0" unfolding less_float_def by auto
  2417 
  2418   have inv: "inverse u1 \<le> inverse (interpret_floatarith a xs)
  2419            \<and> inverse (interpret_floatarith a xs) \<le> inverse l1"
  2420   proof (cases "0 < l1")
  2421     case True hence "0 < real u1" and "0 < real l1" "0 < interpret_floatarith a xs"
  2422       unfolding less_float_def using l1_le_u1 l1 by auto
  2423     show ?thesis
  2424       unfolding inverse_le_iff_le[OF `0 < real u1` `0 < interpret_floatarith a xs`]
  2425         inverse_le_iff_le[OF `0 < interpret_floatarith a xs` `0 < real l1`]
  2426       using l1 u1 by auto
  2427   next
  2428     case False hence "u1 < 0" using either by blast
  2429     hence "real u1 < 0" and "real l1 < 0" "interpret_floatarith a xs < 0"
  2430       unfolding less_float_def using l1_le_u1 u1 by auto
  2431     show ?thesis
  2432       unfolding inverse_le_iff_le_neg[OF `real u1 < 0` `interpret_floatarith a xs < 0`]
  2433         inverse_le_iff_le_neg[OF `interpret_floatarith a xs < 0` `real l1 < 0`]
  2434       using l1 u1 by auto
  2435   qed
  2436 
  2437   from l' have "l = float_divl prec 1 u1" by (cases "0 < l1 \<or> u1 < 0", auto)
  2438   hence "l \<le> inverse u1" unfolding nonzero_inverse_eq_divide[OF `real u1 \<noteq> 0`] using float_divl[of prec 1 u1] by auto
  2439   also have "\<dots> \<le> inverse (interpret_floatarith a xs)" using inv by auto
  2440   finally have "l \<le> inverse (interpret_floatarith a xs)" .
  2441   moreover
  2442   from u' have "u = float_divr prec 1 l1" by (cases "0 < l1 \<or> u1 < 0", auto)
  2443   hence "inverse l1 \<le> u" unfolding nonzero_inverse_eq_divide[OF `real l1 \<noteq> 0`] using float_divr[of 1 l1 prec] by auto
  2444   hence "inverse (interpret_floatarith a xs) \<le> u" by (rule order_trans[OF inv[THEN conjunct2]])
  2445   ultimately show ?case unfolding interpret_floatarith.simps using l1 u1 by auto
  2446 next
  2447   case (Abs x)
  2448   from lift_un'[OF Abs.prems[unfolded approx.simps], unfolded fst_conv snd_conv] Abs.hyps
  2449   obtain l1 u1 where l': "l = (if l1 < 0 \<and> 0 < u1 then 0 else min \<bar>l1\<bar> \<bar>u1\<bar>)" and u': "u = max \<bar>l1\<bar> \<bar>u1\<bar>"
  2450     and l1: "l1 \<le> interpret_floatarith x xs" and u1: "interpret_floatarith x xs \<le> u1" by blast
  2451   thus ?case unfolding l' u' by (cases "l1 < 0 \<and> 0 < u1", auto simp add: real_of_float_min real_of_float_max real_of_float_abs less_float_def)
  2452 next
  2453   case (Min a b)
  2454   from lift_bin'[OF Min.prems[unfolded approx.simps], unfolded fst_conv snd_conv] Min.hyps
  2455   obtain l1 u1 l2 u2 where l': "l = min l1 l2" and u': "u = min u1 u2"
  2456     and l1: "l1 \<le> interpret_floatarith a xs" and u1: "interpret_floatarith a xs \<le> u1"
  2457     and l1: "l2 \<le> interpret_floatarith b xs" and u1: "interpret_floatarith b xs \<le> u2" by blast
  2458   thus ?case unfolding l' u' by (auto simp add: real_of_float_min)
  2459 next
  2460   case (Max a b)
  2461   from lift_bin'[OF Max.prems[unfolded approx.simps], unfolded fst_conv snd_conv] Max.hyps
  2462   obtain l1 u1 l2 u2 where l': "l = max l1 l2" and u': "u = max u1 u2"
  2463     and l1: "l1 \<le> interpret_floatarith a xs" and u1: "interpret_floatarith a xs \<le> u1"
  2464     and l1: "l2 \<le> interpret_floatarith b xs" and u1: "interpret_floatarith b xs \<le> u2" by blast
  2465   thus ?case unfolding l' u' by (auto simp add: real_of_float_max)
  2466 next case (Cos a) with lift_un'_bnds[OF bnds_cos] show ?case by auto
  2467 next case (Arctan a) with lift_un'_bnds[OF bnds_arctan] show ?case by auto
  2468 next case Pi with pi_boundaries show ?case by auto
  2469 next case (Sqrt a) with lift_un'_bnds[OF bnds_sqrt] show ?case by auto
  2470 next case (Exp a) with lift_un'_bnds[OF bnds_exp] show ?case by auto
  2471 next case (Ln a) with lift_un_bnds[OF bnds_ln] show ?case by auto
  2472 next case (Power a n) with lift_un'_bnds[OF bnds_power] show ?case by auto
  2473 next case (Num f) thus ?case by auto
  2474 next
  2475   case (Var n)
  2476   from this[symmetric] `bounded_by xs vs`[THEN bounded_byE, of n]
  2477   show ?case by (cases "n < length vs", auto)
  2478 qed
  2479 
  2480 datatype form = Bound floatarith floatarith floatarith form
  2481               | Assign floatarith floatarith form
  2482               | Less floatarith floatarith
  2483               | LessEqual floatarith floatarith
  2484               | AtLeastAtMost floatarith floatarith floatarith
  2485 
  2486 fun interpret_form :: "form \<Rightarrow> real list \<Rightarrow> bool" where
  2487 "interpret_form (Bound x a b f) vs = (interpret_floatarith x vs \<in> { interpret_floatarith a vs .. interpret_floatarith b vs } \<longrightarrow> interpret_form f vs)" |
  2488 "interpret_form (Assign x a f) vs  = (interpret_floatarith x vs = interpret_floatarith a vs \<longrightarrow> interpret_form f vs)" |
  2489 "interpret_form (Less a b) vs      = (interpret_floatarith a vs < interpret_floatarith b vs)" |
  2490 "interpret_form (LessEqual a b) vs = (interpret_floatarith a vs \<le> interpret_floatarith b vs)" |
  2491 "interpret_form (AtLeastAtMost x a b) vs = (interpret_floatarith x vs \<in> { interpret_floatarith a vs .. interpret_floatarith b vs })"
  2492 
  2493 fun approx_form' and approx_form :: "nat \<Rightarrow> form \<Rightarrow> (float * float) option list \<Rightarrow> nat list \<Rightarrow> bool" where
  2494 "approx_form' prec f 0 n l u bs ss = approx_form prec f (bs[n := Some (l, u)]) ss" |
  2495 "approx_form' prec f (Suc s) n l u bs ss =
  2496   (let m = (l + u) * Float 1 -1
  2497    in (if approx_form' prec f s n l m bs ss then approx_form' prec f s n m u bs ss else False))" |
  2498 "approx_form prec (Bound (Var n) a b f) bs ss =
  2499    (case (approx prec a bs, approx prec b bs)
  2500    of (Some (l, _), Some (_, u)) \<Rightarrow> approx_form' prec f (ss ! n) n l u bs ss
  2501     | _ \<Rightarrow> False)" |
  2502 "approx_form prec (Assign (Var n) a f) bs ss =
  2503    (case (approx prec a bs)
  2504    of (Some (l, u)) \<Rightarrow> approx_form' prec f (ss ! n) n l u bs ss
  2505     | _ \<Rightarrow> False)" |
  2506 "approx_form prec (Less a b) bs ss =
  2507    (case (approx prec a bs, approx prec b bs)
  2508    of (Some (l, u), Some (l', u')) \<Rightarrow> u < l'
  2509     | _ \<Rightarrow> False)" |
  2510 "approx_form prec (LessEqual a b) bs ss =
  2511    (case (approx prec a bs, approx prec b bs)
  2512    of (Some (l, u), Some (l', u')) \<Rightarrow> u \<le> l'
  2513     | _ \<Rightarrow> False)" |
  2514 "approx_form prec (AtLeastAtMost x a b) bs ss =
  2515    (case (approx prec x bs, approx prec a bs, approx prec b bs)
  2516    of (Some (lx, ux), Some (l, u), Some (l', u')) \<Rightarrow> u \<le> lx \<and> ux \<le> l'
  2517     | _ \<Rightarrow> False)" |
  2518 "approx_form _ _ _ _ = False"
  2519 
  2520 lemma lazy_conj: "(if A then B else False) = (A \<and> B)" by simp
  2521 
  2522 lemma approx_form_approx_form':
  2523   assumes "approx_form' prec f s n l u bs ss" and "(x::real) \<in> { l .. u }"
  2524   obtains l' u' where "x \<in> { l' .. u' }"
  2525   and "approx_form prec f (bs[n := Some (l', u')]) ss"
  2526 using assms proof (induct s arbitrary: l u)
  2527   case 0
  2528   from this(1)[of l u] this(2,3)
  2529   show thesis by auto
  2530 next
  2531   case (Suc s)
  2532 
  2533   let ?m = "(l + u) * Float 1 -1"
  2534   have "real l \<le> ?m" and "?m \<le> real u"
  2535     unfolding le_float_def using Suc.prems by auto
  2536 
  2537   with `x \<in> { l .. u }`
  2538   have "x \<in> { l .. ?m} \<or> x \<in> { ?m .. u }" by auto
  2539   thus thesis
  2540   proof (rule disjE)
  2541     assume *: "x \<in> { l .. ?m }"
  2542     with Suc.hyps[OF _ _ *] Suc.prems
  2543     show thesis by (simp add: Let_def lazy_conj)
  2544   next
  2545     assume *: "x \<in> { ?m .. u }"
  2546     with Suc.hyps[OF _ _ *] Suc.prems
  2547     show thesis by (simp add: Let_def lazy_conj)
  2548   qed
  2549 qed
  2550 
  2551 lemma approx_form_aux:
  2552   assumes "approx_form prec f vs ss"
  2553   and "bounded_by xs vs"
  2554   shows "interpret_form f xs"
  2555 using assms proof (induct f arbitrary: vs)
  2556   case (Bound x a b f)
  2557   then obtain n
  2558     where x_eq: "x = Var n" by (cases x) auto
  2559 
  2560   with Bound.prems obtain l u' l' u
  2561     where l_eq: "Some (l, u') = approx prec a vs"
  2562     and u_eq: "Some (l', u) = approx prec b vs"
  2563     and approx_form': "approx_form' prec f (ss ! n) n l u vs ss"
  2564     by (cases "approx prec a vs", simp) (cases "approx prec b vs", auto)
  2565 
  2566   { assume "xs ! n \<in> { interpret_floatarith a xs .. interpret_floatarith b xs }"
  2567     with approx[OF Bound.prems(2) l_eq] and approx[OF Bound.prems(2) u_eq]
  2568     have "xs ! n \<in> { l .. u}" by auto
  2569 
  2570     from approx_form_approx_form'[OF approx_form' this]
  2571     obtain lx ux where bnds: "xs ! n \<in> { lx .. ux }"
  2572       and approx_form: "approx_form prec f (vs[n := Some (lx, ux)]) ss" .
  2573 
  2574     from `bounded_by xs vs` bnds
  2575     have "bounded_by xs (vs[n := Some (lx, ux)])" by (rule bounded_by_update)
  2576     with Bound.hyps[OF approx_form]
  2577     have "interpret_form f xs" by blast }
  2578   thus ?case using interpret_form.simps x_eq and interpret_floatarith.simps by simp
  2579 next
  2580   case (Assign x a f)
  2581   then obtain n
  2582     where x_eq: "x = Var n" by (cases x) auto
  2583 
  2584   with Assign.prems obtain l u' l' u
  2585     where bnd_eq: "Some (l, u) = approx prec a vs"
  2586     and x_eq: "x = Var n"
  2587     and approx_form': "approx_form' prec f (ss ! n) n l u vs ss"
  2588     by (cases "approx prec a vs") auto
  2589 
  2590   { assume bnds: "xs ! n = interpret_floatarith a xs"
  2591     with approx[OF Assign.prems(2) bnd_eq]
  2592     have "xs ! n \<in> { l .. u}" by auto
  2593     from approx_form_approx_form'[OF approx_form' this]
  2594     obtain lx ux where bnds: "xs ! n \<in> { lx .. ux }"
  2595       and approx_form: "approx_form prec f (vs[n := Some (lx, ux)]) ss" .
  2596 
  2597     from `bounded_by xs vs` bnds
  2598     have "bounded_by xs (vs[n := Some (lx, ux)])" by (rule bounded_by_update)
  2599     with Assign.hyps[OF approx_form]
  2600     have "interpret_form f xs" by blast }
  2601   thus ?case using interpret_form.simps x_eq and interpret_floatarith.simps by simp
  2602 next
  2603   case (Less a b)
  2604   then obtain l u l' u'
  2605     where l_eq: "Some (l, u) = approx prec a vs"
  2606     and u_eq: "Some (l', u') = approx prec b vs"
  2607     and inequality: "u < l'"
  2608     by (cases "approx prec a vs", auto,
  2609       cases "approx prec b vs", auto)
  2610   from inequality[unfolded less_float_def] approx[OF Less.prems(2) l_eq] approx[OF Less.prems(2) u_eq]
  2611   show ?case by auto
  2612 next
  2613   case (LessEqual a b)
  2614   then obtain l u l' u'
  2615     where l_eq: "Some (l, u) = approx prec a vs"
  2616     and u_eq: "Some (l', u') = approx prec b vs"
  2617     and inequality: "u \<le> l'"
  2618     by (cases "approx prec a vs", auto,
  2619       cases "approx prec b vs", auto)
  2620   from inequality[unfolded le_float_def] approx[OF LessEqual.prems(2) l_eq] approx[OF LessEqual.prems(2) u_eq]
  2621   show ?case by auto
  2622 next
  2623   case (AtLeastAtMost x a b)
  2624   then obtain lx ux l u l' u'
  2625     where x_eq: "Some (lx, ux) = approx prec x vs"
  2626     and l_eq: "Some (l, u) = approx prec a vs"
  2627     and u_eq: "Some (l', u') = approx prec b vs"
  2628     and inequality: "u \<le> lx \<and> ux \<le> l'"
  2629     by (cases "approx prec x vs", auto,
  2630       cases "approx prec a vs", auto,
  2631       cases "approx prec b vs", auto, blast)
  2632   from inequality[unfolded le_float_def] approx[OF AtLeastAtMost.prems(2) l_eq] approx[OF AtLeastAtMost.prems(2) u_eq] approx[OF AtLeastAtMost.prems(2) x_eq]
  2633   show ?case by auto
  2634 qed
  2635 
  2636 lemma approx_form:
  2637   assumes "n = length xs"
  2638   assumes "approx_form prec f (replicate n None) ss"
  2639   shows "interpret_form f xs"
  2640   using approx_form_aux[OF _ bounded_by_None] assms by auto
  2641 
  2642 subsection {* Implementing Taylor series expansion *}
  2643 
  2644 fun isDERIV :: "nat \<Rightarrow> floatarith \<Rightarrow> real list \<Rightarrow> bool" where
  2645 "isDERIV x (Add a b) vs         = (isDERIV x a vs \<and> isDERIV x b vs)" |
  2646 "isDERIV x (Mult a b) vs        = (isDERIV x a vs \<and> isDERIV x b vs)" |
  2647 "isDERIV x (Minus a) vs         = isDERIV x a vs" |
  2648 "isDERIV x (Inverse a) vs       = (isDERIV x a vs \<and> interpret_floatarith a vs \<noteq> 0)" |
  2649 "isDERIV x (Cos a) vs           = isDERIV x a vs" |
  2650 "isDERIV x (Arctan a) vs        = isDERIV x a vs" |
  2651 "isDERIV x (Min a b) vs         = False" |
  2652 "isDERIV x (Max a b) vs         = False" |
  2653 "isDERIV x (Abs a) vs           = False" |
  2654 "isDERIV x Pi vs                = True" |
  2655 "isDERIV x (Sqrt a) vs          = (isDERIV x a vs \<and> interpret_floatarith a vs > 0)" |
  2656 "isDERIV x (Exp a) vs           = isDERIV x a vs" |
  2657 "isDERIV x (Ln a) vs            = (isDERIV x a vs \<and> interpret_floatarith a vs > 0)" |
  2658 "isDERIV x (Power a 0) vs       = True" |
  2659 "isDERIV x (Power a (Suc n)) vs = isDERIV x a vs" |
  2660 "isDERIV x (Num f) vs           = True" |
  2661 "isDERIV x (Var n) vs          = True"
  2662 
  2663 fun DERIV_floatarith :: "nat \<Rightarrow> floatarith \<Rightarrow> floatarith" where
  2664 "DERIV_floatarith x (Add a b)         = Add (DERIV_floatarith x a) (DERIV_floatarith x b)" |
  2665 "DERIV_floatarith x (Mult a b)        = Add (Mult a (DERIV_floatarith x b)) (Mult (DERIV_floatarith x a) b)" |
  2666 "DERIV_floatarith x (Minus a)         = Minus (DERIV_floatarith x a)" |
  2667 "DERIV_floatarith x (Inverse a)       = Minus (Mult (DERIV_floatarith x a) (Inverse (Power a 2)))" |
  2668 "DERIV_floatarith x (Cos a)           = Minus (Mult (Cos (Add (Mult Pi (Num (Float 1 -1))) (Minus a))) (DERIV_floatarith x a))" |
  2669 "DERIV_floatarith x (Arctan a)        = Mult (Inverse (Add (Num 1) (Power a 2))) (DERIV_floatarith x a)" |
  2670 "DERIV_floatarith x (Min a b)         = Num 0" |
  2671 "DERIV_floatarith x (Max a b)         = Num 0" |
  2672 "DERIV_floatarith x (Abs a)           = Num 0" |
  2673 "DERIV_floatarith x Pi                = Num 0" |
  2674 "DERIV_floatarith x (Sqrt a)          = (Mult (Inverse (Mult (Sqrt a) (Num 2))) (DERIV_floatarith x a))" |
  2675 "DERIV_floatarith x (Exp a)           = Mult (Exp a) (DERIV_floatarith x a)" |
  2676 "DERIV_floatarith x (Ln a)            = Mult (Inverse a) (DERIV_floatarith x a)" |
  2677 "DERIV_floatarith x (Power a 0)       = Num 0" |
  2678 "DERIV_floatarith x (Power a (Suc n)) = Mult (Num (Float (int (Suc n)) 0)) (Mult (Power a n) (DERIV_floatarith x a))" |
  2679 "DERIV_floatarith x (Num f)           = Num 0" |
  2680 "DERIV_floatarith x (Var n)          = (if x = n then Num 1 else Num 0)"
  2681 
  2682 lemma DERIV_floatarith:
  2683   assumes "n < length vs"
  2684   assumes isDERIV: "isDERIV n f (vs[n := x])"
  2685   shows "DERIV (\<lambda> x'. interpret_floatarith f (vs[n := x'])) x :>
  2686                interpret_floatarith (DERIV_floatarith n f) (vs[n := x])"
  2687    (is "DERIV (?i f) x :> _")
  2688 using isDERIV proof (induct f arbitrary: x)
  2689      case (Inverse a) thus ?case
  2690     by (auto intro!: DERIV_intros
  2691              simp add: algebra_simps power2_eq_square)
  2692 next case (Cos a) thus ?case
  2693   by (auto intro!: DERIV_intros
  2694            simp del: interpret_floatarith.simps(5)
  2695            simp add: interpret_floatarith_sin interpret_floatarith.simps(5)[of a])
  2696 next case (Power a n) thus ?case
  2697   by (cases n, auto intro!: DERIV_intros
  2698                     simp del: power_Suc simp add: real_eq_of_nat)
  2699 next case (Ln a) thus ?case
  2700     by (auto intro!: DERIV_intros simp add: divide_inverse)
  2701 next case (Var i) thus ?case using `n < length vs` by auto
  2702 qed (auto intro!: DERIV_intros)
  2703 
  2704 declare approx.simps[simp del]
  2705 
  2706 fun isDERIV_approx :: "nat \<Rightarrow> nat \<Rightarrow> floatarith \<Rightarrow> (float * float) option list \<Rightarrow> bool" where
  2707 "isDERIV_approx prec x (Add a b) vs         = (isDERIV_approx prec x a vs \<and> isDERIV_approx prec x b vs)" |
  2708 "isDERIV_approx prec x (Mult a b) vs        = (isDERIV_approx prec x a vs \<and> isDERIV_approx prec x b vs)" |
  2709 "isDERIV_approx prec x (Minus a) vs         = isDERIV_approx prec x a vs" |
  2710 "isDERIV_approx prec x (Inverse a) vs       =
  2711   (isDERIV_approx prec x a vs \<and> (case approx prec a vs of Some (l, u) \<Rightarrow> 0 < l \<or> u < 0 | None \<Rightarrow> False))" |
  2712 "isDERIV_approx prec x (Cos a) vs           = isDERIV_approx prec x a vs" |
  2713 "isDERIV_approx prec x (Arctan a) vs        = isDERIV_approx prec x a vs" |
  2714 "isDERIV_approx prec x (Min a b) vs         = False" |
  2715 "isDERIV_approx prec x (Max a b) vs         = False" |
  2716 "isDERIV_approx prec x (Abs a) vs           = False" |
  2717 "isDERIV_approx prec x Pi vs                = True" |
  2718 "isDERIV_approx prec x (Sqrt a) vs          =
  2719   (isDERIV_approx prec x a vs \<and> (case approx prec a vs of Some (l, u) \<Rightarrow> 0 < l | None \<Rightarrow> False))" |
  2720 "isDERIV_approx prec x (Exp a) vs           = isDERIV_approx prec x a vs" |
  2721 "isDERIV_approx prec x (Ln a) vs            =
  2722   (isDERIV_approx prec x a vs \<and> (case approx prec a vs of Some (l, u) \<Rightarrow> 0 < l | None \<Rightarrow> False))" |
  2723 "isDERIV_approx prec x (Power a 0) vs       = True" |
  2724 "isDERIV_approx prec x (Power a (Suc n)) vs = isDERIV_approx prec x a vs" |
  2725 "isDERIV_approx prec x (Num f) vs           = True" |
  2726 "isDERIV_approx prec x (Var n) vs          = True"
  2727 
  2728 lemma isDERIV_approx:
  2729   assumes "bounded_by xs vs"
  2730   and isDERIV_approx: "isDERIV_approx prec x f vs"
  2731   shows "isDERIV x f xs"
  2732 using isDERIV_approx proof (induct f)
  2733   case (Inverse a)
  2734   then obtain l u where approx_Some: "Some (l, u) = approx prec a vs"
  2735     and *: "0 < l \<or> u < 0"
  2736     by (cases "approx prec a vs", auto)
  2737   with approx[OF `bounded_by xs vs` approx_Some]
  2738   have "interpret_floatarith a xs \<noteq> 0" unfolding less_float_def by auto
  2739   thus ?case using Inverse by auto
  2740 next
  2741   case (Ln a)
  2742   then obtain l u where approx_Some: "Some (l, u) = approx prec a vs"
  2743     and *: "0 < l"
  2744     by (cases "approx prec a vs", auto)
  2745   with approx[OF `bounded_by xs vs` approx_Some]
  2746   have "0 < interpret_floatarith a xs" unfolding less_float_def by auto
  2747   thus ?case using Ln by auto
  2748 next
  2749   case (Sqrt a)
  2750   then obtain l u where approx_Some: "Some (l, u) = approx prec a vs"
  2751     and *: "0 < l"
  2752     by (cases "approx prec a vs", auto)
  2753   with approx[OF `bounded_by xs vs` approx_Some]
  2754   have "0 < interpret_floatarith a xs" unfolding less_float_def by auto
  2755   thus ?case using Sqrt by auto
  2756 next
  2757   case (Power a n) thus ?case by (cases n, auto)
  2758 qed auto
  2759 
  2760 lemma bounded_by_update_var:
  2761   assumes "bounded_by xs vs" and "vs ! i = Some (l, u)"
  2762   and bnd: "x \<in> { real l .. real u }"
  2763   shows "bounded_by (xs[i := x]) vs"
  2764 proof (cases "i < length xs")
  2765   case False thus ?thesis using `bounded_by xs vs` by auto
  2766 next
  2767   let ?xs = "xs[i := x]"
  2768   case True hence "i < length ?xs" by auto
  2769 { fix j
  2770   assume "j < length vs"
  2771   have "case vs ! j of None \<Rightarrow> True | Some (l, u) \<Rightarrow> ?xs ! j \<in> { real l .. real u }"
  2772   proof (cases "vs ! j")
  2773     case (Some b)
  2774     thus ?thesis
  2775     proof (cases "i = j")
  2776       case True
  2777       thus ?thesis using `vs ! i = Some (l, u)` Some and bnd `i < length ?xs`
  2778         by auto
  2779     next
  2780       case False
  2781       thus ?thesis using `bounded_by xs vs`[THEN bounded_byE, OF `j < length vs`] Some
  2782         by auto
  2783     qed
  2784   qed auto }
  2785   thus ?thesis unfolding bounded_by_def by auto
  2786 qed
  2787 
  2788 lemma isDERIV_approx':
  2789   assumes "bounded_by xs vs"
  2790   and vs_x: "vs ! x = Some (l, u)" and X_in: "X \<in> { real l .. real u }"
  2791   and approx: "isDERIV_approx prec x f vs"
  2792   shows "isDERIV x f (xs[x := X])"
  2793 proof -
  2794   note bounded_by_update_var[OF `bounded_by xs vs` vs_x X_in] approx
  2795   thus ?thesis by (rule isDERIV_approx)
  2796 qed
  2797 
  2798 lemma DERIV_approx:
  2799   assumes "n < length xs" and bnd: "bounded_by xs vs"
  2800   and isD: "isDERIV_approx prec n f vs"
  2801   and app: "Some (l, u) = approx prec (DERIV_floatarith n f) vs" (is "_ = approx _ ?D _")
  2802   shows "\<exists>(x::real). l \<le> x \<and> x \<le> u \<and>
  2803              DERIV (\<lambda> x. interpret_floatarith f (xs[n := x])) (xs!n) :> x"
  2804          (is "\<exists> x. _ \<and> _ \<and> DERIV (?i f) _ :> _")
  2805 proof (rule exI[of _ "?i ?D (xs!n)"], rule conjI[OF _ conjI])
  2806   let "?i f x" = "interpret_floatarith f (xs[n := x])"
  2807   from approx[OF bnd app]
  2808   show "l \<le> ?i ?D (xs!n)" and "?i ?D (xs!n) \<le> u"
  2809     using `n < length xs` by auto
  2810   from DERIV_floatarith[OF `n < length xs`, of f "xs!n"] isDERIV_approx[OF bnd isD]
  2811   show "DERIV (?i f) (xs!n) :> (?i ?D (xs!n))" by simp
  2812 qed
  2813 
  2814 fun lift_bin :: "(float * float) option \<Rightarrow> (float * float) option \<Rightarrow> (float \<Rightarrow> float \<Rightarrow> float \<Rightarrow> float \<Rightarrow> (float * float) option) \<Rightarrow> (float * float) option" where
  2815 "lift_bin (Some (l1, u1)) (Some (l2, u2)) f = f l1 u1 l2 u2" |
  2816 "lift_bin a b f = None"
  2817 
  2818 lemma lift_bin:
  2819   assumes lift_bin_Some: "Some (l, u) = lift_bin a b f"
  2820   obtains l1 u1 l2 u2
  2821   where "a = Some (l1, u1)"
  2822   and "b = Some (l2, u2)"
  2823   and "f l1 u1 l2 u2 = Some (l, u)"
  2824 using assms by (cases a, simp, cases b, simp, auto)
  2825 
  2826 fun approx_tse where
  2827 "approx_tse prec n 0 c k f bs = approx prec f bs" |
  2828 "approx_tse prec n (Suc s) c k f bs =
  2829   (if isDERIV_approx prec n f bs then
  2830     lift_bin (approx prec f (bs[n := Some (c,c)]))
  2831              (approx_tse prec n s c (Suc k) (DERIV_floatarith n f) bs)
  2832              (\<lambda> l1 u1 l2 u2. approx prec
  2833                  (Add (Var 0)
  2834                       (Mult (Inverse (Num (Float (int k) 0)))
  2835                                  (Mult (Add (Var (Suc (Suc 0))) (Minus (Num c)))
  2836                                        (Var (Suc 0))))) [Some (l1, u1), Some (l2, u2), bs!n])
  2837   else approx prec f bs)"
  2838 
  2839 lemma bounded_by_Cons:
  2840   assumes bnd: "bounded_by xs vs"
  2841   and x: "x \<in> { real l .. real u }"
  2842   shows "bounded_by (x#xs) ((Some (l, u))#vs)"
  2843 proof -
  2844   { fix i assume *: "i < length ((Some (l, u))#vs)"
  2845     have "case ((Some (l,u))#vs) ! i of Some (l, u) \<Rightarrow> (x#xs)!i \<in> { real l .. real u } | None \<Rightarrow> True"
  2846     proof (cases i)
  2847       case 0 with x show ?thesis by auto
  2848     next
  2849       case (Suc i) with * have "i < length vs" by auto
  2850       from bnd[THEN bounded_byE, OF this]
  2851       show ?thesis unfolding Suc nth_Cons_Suc .
  2852     qed }
  2853   thus ?thesis by (auto simp add: bounded_by_def)
  2854 qed
  2855 
  2856 lemma approx_tse_generic:
  2857   assumes "bounded_by xs vs"
  2858   and bnd_c: "bounded_by (xs[x := c]) vs" and "x < length vs" and "x < length xs"
  2859   and bnd_x: "vs ! x = Some (lx, ux)"
  2860   and ate: "Some (l, u) = approx_tse prec x s c k f vs"
  2861   shows "\<exists> n. (\<forall> m < n. \<forall> (z::real) \<in> {lx .. ux}.
  2862       DERIV (\<lambda> y. interpret_floatarith ((DERIV_floatarith x ^^ m) f) (xs[x := y])) z :>
  2863             (interpret_floatarith ((DERIV_floatarith x ^^ (Suc m)) f) (xs[x := z])))
  2864    \<and> (\<forall> (t::real) \<in> {lx .. ux}.  (\<Sum> i = 0..<n. inverse (real (\<Prod> j \<in> {k..<k+i}. j)) *
  2865                   interpret_floatarith ((DERIV_floatarith x ^^ i) f) (xs[x := c]) *
  2866                   (xs!x - c)^i) +
  2867       inverse (real (\<Prod> j \<in> {k..<k+n}. j)) *
  2868       interpret_floatarith ((DERIV_floatarith x ^^ n) f) (xs[x := t]) *
  2869       (xs!x - c)^n \<in> {l .. u})" (is "\<exists> n. ?taylor f k l u n")
  2870 using ate proof (induct s arbitrary: k f l u)
  2871   case 0
  2872   { fix t::real assume "t \<in> {lx .. ux}"
  2873     note bounded_by_update_var[OF `bounded_by xs vs` bnd_x this]
  2874     from approx[OF this 0[unfolded approx_tse.simps]]
  2875     have "(interpret_floatarith f (xs[x := t])) \<in> {l .. u}"
  2876       by (auto simp add: algebra_simps)
  2877   } thus ?case by (auto intro!: exI[of _ 0])
  2878 next
  2879   case (Suc s)
  2880   show ?case
  2881   proof (cases "isDERIV_approx prec x f vs")
  2882     case False
  2883     note ap = Suc.prems[unfolded approx_tse.simps if_not_P[OF False]]
  2884 
  2885     { fix t::real assume "t \<in> {lx .. ux}"
  2886       note bounded_by_update_var[OF `bounded_by xs vs` bnd_x this]
  2887       from approx[OF this ap]
  2888       have "(interpret_floatarith f (xs[x := t])) \<in> {l .. u}"
  2889         by (auto simp add: algebra_simps)
  2890     } thus ?thesis by (auto intro!: exI[of _ 0])
  2891   next
  2892     case True
  2893     with Suc.prems
  2894     obtain l1 u1 l2 u2
  2895       where a: "Some (l1, u1) = approx prec f (vs[x := Some (c,c)])"
  2896       and ate: "Some (l2, u2) = approx_tse prec x s c (Suc k) (DERIV_floatarith x f) vs"
  2897       and final: "Some (l, u) = approx prec
  2898         (Add (Var 0)
  2899              (Mult (Inverse (Num (Float (int k) 0)))
  2900                    (Mult (Add (Var (Suc (Suc 0))) (Minus (Num c)))
  2901                          (Var (Suc 0))))) [Some (l1, u1), Some (l2, u2), vs!x]"
  2902       by (auto elim!: lift_bin) blast
  2903 
  2904     from bnd_c `x < length xs`
  2905     have bnd: "bounded_by (xs[x:=c]) (vs[x:= Some (c,c)])"
  2906       by (auto intro!: bounded_by_update)
  2907 
  2908     from approx[OF this a]
  2909     have f_c: "interpret_floatarith ((DERIV_floatarith x ^^ 0) f) (xs[x := c]) \<in> { l1 .. u1 }"
  2910               (is "?f 0 (real c) \<in> _")
  2911       by auto
  2912 
  2913     { fix f :: "'a \<Rightarrow> 'a" fix n :: nat fix x :: 'a
  2914       have "(f ^^ Suc n) x = (f ^^ n) (f x)"
  2915         by (induct n, auto) }
  2916     note funpow_Suc = this[symmetric]
  2917     from Suc.hyps[OF ate, unfolded this]
  2918     obtain n
  2919       where DERIV_hyp: "\<And> m z. \<lbrakk> m < n ; (z::real) \<in> { lx .. ux } \<rbrakk> \<Longrightarrow> DERIV (?f (Suc m)) z :> ?f (Suc (Suc m)) z"
  2920       and hyp: "\<forall> t \<in> {real lx .. real ux}. (\<Sum> i = 0..<n. inverse (real (\<Prod> j \<in> {Suc k..<Suc k + i}. j)) * ?f (Suc i) c * (xs!x - c)^i) +
  2921            inverse (real (\<Prod> j \<in> {Suc k..<Suc k + n}. j)) * ?f (Suc n) t * (xs!x - c)^n \<in> {l2 .. u2}"
  2922           (is "\<forall> t \<in> _. ?X (Suc k) f n t \<in> _")
  2923       by blast
  2924 
  2925     { fix m and z::real
  2926       assume "m < Suc n" and bnd_z: "z \<in> { lx .. ux }"
  2927       have "DERIV (?f m) z :> ?f (Suc m) z"
  2928       proof (cases m)
  2929         case 0
  2930         with DERIV_floatarith[OF `x < length xs` isDERIV_approx'[OF `bounded_by xs vs` bnd_x bnd_z True]]
  2931         show ?thesis by simp
  2932       next
  2933         case (Suc m')
  2934         hence "m' < n" using `m < Suc n` by auto
  2935         from DERIV_hyp[OF this bnd_z]
  2936         show ?thesis using Suc by simp
  2937       qed } note DERIV = this
  2938 
  2939     have "\<And> k i. k < i \<Longrightarrow> {k ..< i} = insert k {Suc k ..< i}" by auto
  2940     hence setprod_head_Suc: "\<And> k i. \<Prod> {k ..< k + Suc i} = k * \<Prod> {Suc k ..< Suc k + i}" by auto
  2941     have setsum_move0: "\<And> k F. setsum F {0..<Suc k} = F 0 + setsum (\<lambda> k. F (Suc k)) {0..<k}"
  2942       unfolding setsum_shift_bounds_Suc_ivl[symmetric]
  2943       unfolding setsum_head_upt_Suc[OF zero_less_Suc] ..
  2944     def C \<equiv> "xs!x - c"
  2945 
  2946     { fix t::real assume t: "t \<in> {lx .. ux}"
  2947       hence "bounded_by [xs!x] [vs!x]"
  2948         using `bounded_by xs vs`[THEN bounded_byE, OF `x < length vs`]
  2949         by (cases "vs!x", auto simp add: bounded_by_def)
  2950 
  2951       with hyp[THEN bspec, OF t] f_c
  2952       have "bounded_by [?f 0 c, ?X (Suc k) f n t, xs!x] [Some (l1, u1), Some (l2, u2), vs!x]"
  2953         by (auto intro!: bounded_by_Cons)
  2954       from approx[OF this final, unfolded atLeastAtMost_iff[symmetric]]
  2955       have "?X (Suc k) f n t * (xs!x - real c) * inverse k + ?f 0 c \<in> {l .. u}"
  2956         by (auto simp add: algebra_simps)
  2957       also have "?X (Suc k) f n t * (xs!x - real c) * inverse (real k) + ?f 0 c =
  2958                (\<Sum> i = 0..<Suc n. inverse (real (\<Prod> j \<in> {k..<k+i}. j)) * ?f i c * (xs!x - c)^i) +
  2959                inverse (real (\<Prod> j \<in> {k..<k+Suc n}. j)) * ?f (Suc n) t * (xs!x - c)^Suc n" (is "_ = ?T")
  2960         unfolding funpow_Suc C_def[symmetric] setsum_move0 setprod_head_Suc
  2961         by (auto simp add: algebra_simps)
  2962           (simp only: mult_left_commute [of _ "inverse (real k)"] setsum_right_distrib [symmetric])
  2963       finally have "?T \<in> {l .. u}" . }
  2964     thus ?thesis using DERIV by blast
  2965   qed
  2966 qed
  2967 
  2968 lemma setprod_fact: "\<Prod> {1..<1 + k} = fact (k :: nat)"
  2969 proof (induct k)
  2970   case (Suc k)
  2971   have "{ 1 ..< Suc (Suc k) } = insert (Suc k) { 1 ..< Suc k }" by auto
  2972   hence "\<Prod> { 1 ..< Suc (Suc k) } = (Suc k) * \<Prod> { 1 ..< Suc k }" by auto
  2973   thus ?case using Suc by auto
  2974 qed simp
  2975 
  2976 lemma approx_tse:
  2977   assumes "bounded_by xs vs"
  2978   and bnd_x: "vs ! x = Some (lx, ux)" and bnd_c: "real c \<in> {lx .. ux}"
  2979   and "x < length vs" and "x < length xs"
  2980   and ate: "Some (l, u) = approx_tse prec x s c 1 f vs"
  2981   shows "interpret_floatarith f xs \<in> { l .. u }"
  2982 proof -
  2983   def F \<equiv> "\<lambda> n z. interpret_floatarith ((DERIV_floatarith x ^^ n) f) (xs[x := z])"
  2984   hence F0: "F 0 = (\<lambda> z. interpret_floatarith f (xs[x := z]))" by auto
  2985 
  2986   hence "bounded_by (xs[x := c]) vs" and "x < length vs" "x < length xs"
  2987     using `bounded_by xs vs` bnd_x bnd_c `x < length vs` `x < length xs`
  2988     by (auto intro!: bounded_by_update_var)
  2989 
  2990   from approx_tse_generic[OF `bounded_by xs vs` this bnd_x ate]
  2991   obtain n
  2992     where DERIV: "\<forall> m z. m < n \<and> real lx \<le> z \<and> z \<le> real ux \<longrightarrow> DERIV (F m) z :> F (Suc m) z"
  2993     and hyp: "\<And> (t::real). t \<in> {lx .. ux} \<Longrightarrow>
  2994            (\<Sum> j = 0..<n. inverse (real (fact j)) * F j c * (xs!x - c)^j) +
  2995              inverse (real (fact n)) * F n t * (xs!x - c)^n
  2996              \<in> {l .. u}" (is "\<And> t. _ \<Longrightarrow> ?taylor t \<in> _")
  2997     unfolding F_def atLeastAtMost_iff[symmetric] setprod_fact by blast
  2998 
  2999   have bnd_xs: "xs ! x \<in> { lx .. ux }"
  3000     using `bounded_by xs vs`[THEN bounded_byE, OF `x < length vs`] bnd_x by auto
  3001 
  3002   show ?thesis
  3003   proof (cases n)
  3004     case 0 thus ?thesis using hyp[OF bnd_xs] unfolding F_def by auto
  3005   next
  3006     case (Suc n')
  3007     show ?thesis
  3008     proof (cases "xs ! x = c")
  3009       case True
  3010       from True[symmetric] hyp[OF bnd_xs] Suc show ?thesis
  3011         unfolding F_def Suc setsum_head_upt_Suc[OF zero_less_Suc] setsum_shift_bounds_Suc_ivl by auto
  3012     next
  3013       case False
  3014 
  3015       have "lx \<le> real c" "real c \<le> ux" "lx \<le> xs!x" "xs!x \<le> ux"
  3016         using Suc bnd_c `bounded_by xs vs`[THEN bounded_byE, OF `x < length vs`] bnd_x by auto
  3017       from Taylor.taylor[OF zero_less_Suc, of F, OF F0 DERIV[unfolded Suc] this False]
  3018       obtain t::real where t_bnd: "if xs ! x < c then xs ! x < t \<and> t < c else c < t \<and> t < xs ! x"
  3019         and fl_eq: "interpret_floatarith f (xs[x := xs ! x]) =
  3020            (\<Sum>m = 0..<Suc n'. F m c / real (fact m) * (xs ! x - c) ^ m) +
  3021            F (Suc n') t / real (fact (Suc n')) * (xs ! x - c) ^ Suc n'"
  3022         by blast
  3023 
  3024       from t_bnd bnd_xs bnd_c have *: "t \<in> {lx .. ux}"
  3025         by (cases "xs ! x < c", auto)
  3026 
  3027       have "interpret_floatarith f (xs[x := xs ! x]) = ?taylor t"
  3028         unfolding fl_eq Suc by (auto simp add: algebra_simps divide_inverse)
  3029       also have "\<dots> \<in> {l .. u}" using * by (rule hyp)
  3030       finally show ?thesis by simp
  3031     qed
  3032   qed
  3033 qed
  3034 
  3035 fun approx_tse_form' where
  3036 "approx_tse_form' prec t f 0 l u cmp =
  3037   (case approx_tse prec 0 t ((l + u) * Float 1 -1) 1 f [Some (l, u)]
  3038      of Some (l, u) \<Rightarrow> cmp l u | None \<Rightarrow> False)" |
  3039 "approx_tse_form' prec t f (Suc s) l u cmp =
  3040   (let m = (l + u) * Float 1 -1
  3041    in (if approx_tse_form' prec t f s l m cmp then
  3042       approx_tse_form' prec t f s m u cmp else False))"
  3043 
  3044 lemma approx_tse_form':
  3045   fixes x :: real
  3046   assumes "approx_tse_form' prec t f s l u cmp" and "x \<in> {l .. u}"
  3047   shows "\<exists> l' u' ly uy. x \<in> { l' .. u' } \<and> real l \<le> l' \<and> u' \<le> real u \<and> cmp ly uy \<and>
  3048                   approx_tse prec 0 t ((l' + u') * Float 1 -1) 1 f [Some (l', u')] = Some (ly, uy)"
  3049 using assms proof (induct s arbitrary: l u)
  3050   case 0
  3051   then obtain ly uy
  3052     where *: "approx_tse prec 0 t ((l + u) * Float 1 -1) 1 f [Some (l, u)] = Some (ly, uy)"
  3053     and **: "cmp ly uy" by (auto elim!: option_caseE)
  3054   with 0 show ?case by (auto intro!: exI)
  3055 next
  3056   case (Suc s)
  3057   let ?m = "(l + u) * Float 1 -1"
  3058   from Suc.prems
  3059   have l: "approx_tse_form' prec t f s l ?m cmp"
  3060     and u: "approx_tse_form' prec t f s ?m u cmp"
  3061     by (auto simp add: Let_def lazy_conj)
  3062 
  3063   have m_l: "real l \<le> ?m" and m_u: "?m \<le> real u"
  3064     unfolding le_float_def using Suc.prems by auto
  3065 
  3066   with `x \<in> { l .. u }`
  3067   have "x \<in> { l .. ?m} \<or> x \<in> { ?m .. u }" by auto
  3068   thus ?case
  3069   proof (rule disjE)
  3070     assume "x \<in> { l .. ?m}"
  3071     from Suc.hyps[OF l this]
  3072     obtain l' u' ly uy
  3073       where "x \<in> { l' .. u' } \<and> real l \<le> l' \<and> real u' \<le> ?m \<and> cmp ly uy \<and>
  3074                   approx_tse prec 0 t ((l' + u') * Float 1 -1) 1 f [Some (l', u')] = Some (ly, uy)" by blast
  3075     with m_u show ?thesis by (auto intro!: exI)
  3076   next
  3077     assume "x \<in> { ?m .. u }"
  3078     from Suc.hyps[OF u this]
  3079     obtain l' u' ly uy
  3080       where "x \<in> { l' .. u' } \<and> ?m \<le> real l' \<and> u' \<le> real u \<and> cmp ly uy \<and>
  3081                   approx_tse prec 0 t ((l' + u') * Float 1 -1) 1 f [Some (l', u')] = Some (ly, uy)" by blast
  3082     with m_u show ?thesis by (auto intro!: exI)
  3083   qed
  3084 qed
  3085 
  3086 lemma approx_tse_form'_less:
  3087   fixes x :: real
  3088   assumes tse: "approx_tse_form' prec t (Add a (Minus b)) s l u (\<lambda> l u. 0 < l)"
  3089   and x: "x \<in> {l .. u}"
  3090   shows "interpret_floatarith b [x] < interpret_floatarith a [x]"
  3091 proof -
  3092   from approx_tse_form'[OF tse x]
  3093   obtain l' u' ly uy
  3094     where x': "x \<in> { l' .. u' }" and "l \<le> real l'"
  3095     and "real u' \<le> u" and "0 < ly"
  3096     and tse: "approx_tse prec 0 t ((l' + u') * Float 1 -1) 1 (Add a (Minus b)) [Some (l', u')] = Some (ly, uy)"
  3097     by blast
  3098 
  3099   hence "bounded_by [x] [Some (l', u')]" by (auto simp add: bounded_by_def)
  3100 
  3101   from approx_tse[OF this _ _ _ _ tse[symmetric], of l' u'] x'
  3102   have "ly \<le> interpret_floatarith a [x] - interpret_floatarith b [x]"
  3103     by (auto simp add: diff_minus)
  3104   from order_less_le_trans[OF `0 < ly`[unfolded less_float_def] this]
  3105   show ?thesis by auto
  3106 qed
  3107 
  3108 lemma approx_tse_form'_le:
  3109   fixes x :: real
  3110   assumes tse: "approx_tse_form' prec t (Add a (Minus b)) s l u (\<lambda> l u. 0 \<le> l)"
  3111   and x: "x \<in> {l .. u}"
  3112   shows "interpret_floatarith b [x] \<le> interpret_floatarith a [x]"
  3113 proof -
  3114   from approx_tse_form'[OF tse x]
  3115   obtain l' u' ly uy
  3116     where x': "x \<in> { l' .. u' }" and "l \<le> real l'"
  3117     and "real u' \<le> u" and "0 \<le> ly"
  3118     and tse: "approx_tse prec 0 t ((l' + u') * Float 1 -1) 1 (Add a (Minus b)) [Some (l', u')] = Some (ly, uy)"
  3119     by blast
  3120 
  3121   hence "bounded_by [x] [Some (l', u')]" by (auto simp add: bounded_by_def)
  3122 
  3123   from approx_tse[OF this _ _ _ _ tse[symmetric], of l' u'] x'
  3124   have "ly \<le> interpret_floatarith a [x] - interpret_floatarith b [x]"
  3125     by (auto simp add: diff_minus)
  3126   from order_trans[OF `0 \<le> ly`[unfolded le_float_def] this]
  3127   show ?thesis by auto
  3128 qed
  3129 
  3130 definition
  3131 "approx_tse_form prec t s f =
  3132   (case f
  3133    of (Bound x a b f) \<Rightarrow> x = Var 0 \<and>
  3134      (case (approx prec a [None], approx prec b [None])
  3135       of (Some (l, u), Some (l', u')) \<Rightarrow>
  3136         (case f
  3137          of Less lf rt \<Rightarrow> approx_tse_form' prec t (Add rt (Minus lf)) s l u' (\<lambda> l u. 0 < l)
  3138           | LessEqual lf rt \<Rightarrow> approx_tse_form' prec t (Add rt (Minus lf)) s l u' (\<lambda> l u. 0 \<le> l)
  3139           | AtLeastAtMost x lf rt \<Rightarrow>
  3140             (if approx_tse_form' prec t (Add x (Minus lf)) s l u' (\<lambda> l u. 0 \<le> l) then
  3141             approx_tse_form' prec t (Add rt (Minus x)) s l u' (\<lambda> l u. 0 \<le> l) else False)
  3142           | _ \<Rightarrow> False)
  3143        | _ \<Rightarrow> False)
  3144    | _ \<Rightarrow> False)"
  3145 
  3146 lemma approx_tse_form:
  3147   assumes "approx_tse_form prec t s f"
  3148   shows "interpret_form f [x]"
  3149 proof (cases f)
  3150   case (Bound i a b f') note f_def = this
  3151   with assms obtain l u l' u'
  3152     where a: "approx prec a [None] = Some (l, u)"
  3153     and b: "approx prec b [None] = Some (l', u')"
  3154     unfolding approx_tse_form_def by (auto elim!: option_caseE)
  3155 
  3156   from Bound assms have "i = Var 0" unfolding approx_tse_form_def by auto
  3157   hence i: "interpret_floatarith i [x] = x" by auto
  3158 
  3159   { let "?f z" = "interpret_floatarith z [x]"
  3160     assume "?f i \<in> { ?f a .. ?f b }"
  3161     with approx[OF _ a[symmetric], of "[x]"] approx[OF _ b[symmetric], of "[x]"]
  3162     have bnd: "x \<in> { l .. u'}" unfolding bounded_by_def i by auto
  3163 
  3164     have "interpret_form f' [x]"
  3165     proof (cases f')
  3166       case (Less lf rt)
  3167       with Bound a b assms
  3168       have "approx_tse_form' prec t (Add rt (Minus lf)) s l u' (\<lambda> l u. 0 < l)"
  3169         unfolding approx_tse_form_def by auto
  3170       from approx_tse_form'_less[OF this bnd]
  3171       show ?thesis using Less by auto
  3172     next
  3173       case (LessEqual lf rt)
  3174       with Bound a b assms
  3175       have "approx_tse_form' prec t (Add rt (Minus lf)) s l u' (\<lambda> l u. 0 \<le> l)"
  3176         unfolding approx_tse_form_def by auto
  3177       from approx_tse_form'_le[OF this bnd]
  3178       show ?thesis using LessEqual by auto
  3179     next
  3180       case (AtLeastAtMost x lf rt)
  3181       with Bound a b assms
  3182       have "approx_tse_form' prec t (Add rt (Minus x)) s l u' (\<lambda> l u. 0 \<le> l)"
  3183         and "approx_tse_form' prec t (Add x (Minus lf)) s l u' (\<lambda> l u. 0 \<le> l)"
  3184         unfolding approx_tse_form_def lazy_conj by auto
  3185       from approx_tse_form'_le[OF this(1) bnd] approx_tse_form'_le[OF this(2) bnd]
  3186       show ?thesis using AtLeastAtMost by auto
  3187     next
  3188       case (Bound x a b f') with assms
  3189       show ?thesis by (auto elim!: option_caseE simp add: f_def approx_tse_form_def)
  3190     next
  3191       case (Assign x a f') with assms
  3192       show ?thesis by (auto elim!: option_caseE simp add: f_def approx_tse_form_def)
  3193     qed } thus ?thesis unfolding f_def by auto
  3194 next case Assign with assms show ?thesis by (auto simp add: approx_tse_form_def)
  3195 next case LessEqual with assms show ?thesis by (auto simp add: approx_tse_form_def)
  3196 next case Less with assms show ?thesis by (auto simp add: approx_tse_form_def)
  3197 next case AtLeastAtMost with assms show ?thesis by (auto simp add: approx_tse_form_def)
  3198 qed
  3199 
  3200 text {* @{term approx_form_eval} is only used for the {\tt value}-command. *}
  3201 
  3202 fun approx_form_eval :: "nat \<Rightarrow> form \<Rightarrow> (float * float) option list \<Rightarrow> (float * float) option list" where
  3203 "approx_form_eval prec (Bound (Var n) a b f) bs =
  3204    (case (approx prec a bs, approx prec b bs)
  3205    of (Some (l, _), Some (_, u)) \<Rightarrow> approx_form_eval prec f (bs[n := Some (l, u)])
  3206     | _ \<Rightarrow> bs)" |
  3207 "approx_form_eval prec (Assign (Var n) a f) bs =
  3208    (case (approx prec a bs)
  3209    of (Some (l, u)) \<Rightarrow> approx_form_eval prec f (bs[n := Some (l, u)])
  3210     | _ \<Rightarrow> bs)" |
  3211 "approx_form_eval prec (Less a b) bs = bs @ [approx prec a bs, approx prec b bs]" |
  3212 "approx_form_eval prec (LessEqual a b) bs = bs @ [approx prec a bs, approx prec b bs]" |
  3213 "approx_form_eval prec (AtLeastAtMost x a b) bs =
  3214    bs @ [approx prec x bs, approx prec a bs, approx prec b bs]" |
  3215 "approx_form_eval _ _ bs = bs"
  3216 
  3217 subsection {* Implement proof method \texttt{approximation} *}
  3218 
  3219 lemmas interpret_form_equations = interpret_form.simps interpret_floatarith.simps interpret_floatarith_num
  3220   interpret_floatarith_divide interpret_floatarith_diff interpret_floatarith_tan interpret_floatarith_powr interpret_floatarith_log
  3221   interpret_floatarith_sin
  3222 
  3223 oracle approximation_oracle = {* fn (thy, t) =>
  3224 let
  3225 
  3226   fun bad t = error ("Bad term: " ^ Syntax.string_of_term_global thy t);
  3227 
  3228   fun term_of_bool true = @{term True}
  3229     | term_of_bool false = @{term False};
  3230 
  3231   fun term_of_float (@{code Float} (k, l)) =
  3232     @{term Float} $ HOLogic.mk_number @{typ int} k $ HOLogic.mk_number @{typ int} l;
  3233 
  3234   fun term_of_float_float_option NONE = @{term "None :: (float \<times> float) option"}
  3235     | term_of_float_float_option (SOME ff) = @{term "Some :: float \<times> float \<Rightarrow> _"}
  3236         $ HOLogic.mk_prod (pairself term_of_float ff);
  3237 
  3238   val term_of_float_float_option_list =
  3239     HOLogic.mk_list @{typ "(float \<times> float) option"} o map term_of_float_float_option;
  3240 
  3241   fun nat_of_term t = HOLogic.dest_nat t handle TERM _ => snd (HOLogic.dest_number t);
  3242 
  3243   fun float_of_term (@{term Float} $ k $ l) =
  3244         @{code Float} (snd (HOLogic.dest_number k), snd (HOLogic.dest_number l))
  3245     | float_of_term t = bad t;
  3246 
  3247   fun floatarith_of_term (@{term Add} $ a $ b) = @{code Add} (floatarith_of_term a, floatarith_of_term b)
  3248     | floatarith_of_term (@{term Minus} $ a) = @{code Minus} (floatarith_of_term a)
  3249     | floatarith_of_term (@{term Mult} $ a $ b) = @{code Mult} (floatarith_of_term a, floatarith_of_term b)
  3250     | floatarith_of_term (@{term Inverse} $ a) = @{code Inverse} (floatarith_of_term a)
  3251     | floatarith_of_term (@{term Cos} $ a) = @{code Cos} (floatarith_of_term a)
  3252     | floatarith_of_term (@{term Arctan} $ a) = @{code Arctan} (floatarith_of_term a)
  3253     | floatarith_of_term (@{term Abs} $ a) = @{code Abs} (floatarith_of_term a)
  3254     | floatarith_of_term (@{term Max} $ a $ b) = @{code Max} (floatarith_of_term a, floatarith_of_term b)
  3255     | floatarith_of_term (@{term Min} $ a $ b) = @{code Min} (floatarith_of_term a, floatarith_of_term b)
  3256     | floatarith_of_term @{term Pi} = @{code Pi}
  3257     | floatarith_of_term (@{term Sqrt} $ a) = @{code Sqrt} (floatarith_of_term a)
  3258     | floatarith_of_term (@{term Exp} $ a) = @{code Exp} (floatarith_of_term a)
  3259     | floatarith_of_term (@{term Ln} $ a) = @{code Ln} (floatarith_of_term a)
  3260     | floatarith_of_term (@{term Power} $ a $ n) =
  3261         @{code Power} (floatarith_of_term a, nat_of_term n)
  3262     | floatarith_of_term (@{term Var} $ n) = @{code Var} (nat_of_term n)
  3263     | floatarith_of_term (@{term Num} $ m) = @{code Num} (float_of_term m)
  3264     | floatarith_of_term t = bad t;
  3265 
  3266   fun form_of_term (@{term Bound} $ a $ b $ c $ p) = @{code Bound}
  3267         (floatarith_of_term a, floatarith_of_term b, floatarith_of_term c, form_of_term p)
  3268     | form_of_term (@{term Assign} $ a $ b $ p) = @{code Assign}
  3269         (floatarith_of_term a, floatarith_of_term b, form_of_term p)
  3270     | form_of_term (@{term Less} $ a $ b) = @{code Less}
  3271         (floatarith_of_term a, floatarith_of_term b)
  3272     | form_of_term (@{term LessEqual} $ a $ b) = @{code LessEqual}
  3273         (floatarith_of_term a, floatarith_of_term b)
  3274     | form_of_term (@{term AtLeastAtMost} $ a $ b $ c) = @{code AtLeastAtMost}
  3275         (floatarith_of_term a, floatarith_of_term b, floatarith_of_term c)
  3276     | form_of_term t = bad t;
  3277 
  3278   fun float_float_option_of_term @{term "None :: (float \<times> float) option"} = NONE
  3279     | float_float_option_of_term (@{term "Some :: float \<times> float \<Rightarrow> _"} $ ff) =
  3280         SOME (pairself float_of_term (HOLogic.dest_prod ff))
  3281     | float_float_option_of_term (@{term approx'} $ n $ a $ ffs) = @{code approx'}
  3282         (nat_of_term n) (floatarith_of_term a) (float_float_option_list_of_term ffs)
  3283     | float_float_option_of_term t = bad t
  3284   and float_float_option_list_of_term
  3285         (@{term "replicate :: _ \<Rightarrow> (float \<times> float) option \<Rightarrow> _"} $ n $ @{term "None :: (float \<times> float) option"}) =
  3286           @{code replicate} (nat_of_term n) NONE
  3287     | float_float_option_list_of_term (@{term approx_form_eval} $ n $ p $ ffs) =
  3288         @{code approx_form_eval} (nat_of_term n) (form_of_term p) (float_float_option_list_of_term ffs)
  3289     | float_float_option_list_of_term t = map float_float_option_of_term
  3290         (HOLogic.dest_list t);
  3291 
  3292   val nat_list_of_term = map nat_of_term o HOLogic.dest_list ;
  3293 
  3294   fun bool_of_term (@{term approx_form} $ n $ p $ ffs $ ms) = @{code approx_form}
  3295         (nat_of_term n) (form_of_term p) (float_float_option_list_of_term ffs) (nat_list_of_term ms)
  3296     | bool_of_term (@{term approx_tse_form} $ m $ n $ q $ p) =
  3297         @{code approx_tse_form} (nat_of_term m) (nat_of_term n) (nat_of_term q) (form_of_term p)
  3298     | bool_of_term t = bad t;
  3299 
  3300   fun eval t = case fastype_of t
  3301    of @{typ bool} =>
  3302         (term_of_bool o bool_of_term) t
  3303     | @{typ "(float \<times> float) option"} =>
  3304         (term_of_float_float_option o float_float_option_of_term) t
  3305     | @{typ "(float \<times> float) option list"} =>
  3306         (term_of_float_float_option_list o float_float_option_list_of_term) t
  3307     | _ => bad t;
  3308 
  3309   val normalize = eval o Envir.beta_norm o Pattern.eta_long [];
  3310 
  3311 in Thm.cterm_of thy (Logic.mk_equals (t, normalize t)) end
  3312 *}
  3313 
  3314 ML {*
  3315   fun reorder_bounds_tac prems i =
  3316     let
  3317       fun variable_of_bound (Const (@{const_name Trueprop}, _) $
  3318                              (Const (@{const_name Set.member}, _) $
  3319                               Free (name, _) $ _)) = name
  3320         | variable_of_bound (Const (@{const_name Trueprop}, _) $
  3321                              (Const (@{const_name HOL.eq}, _) $
  3322                               Free (name, _) $ _)) = name
  3323         | variable_of_bound t = raise TERM ("variable_of_bound", [t])
  3324 
  3325       val variable_bounds
  3326         = map (` (variable_of_bound o prop_of)) prems
  3327 
  3328       fun add_deps (name, bnds)
  3329         = Graph.add_deps_acyclic (name,
  3330             remove (op =) name (Term.add_free_names (prop_of bnds) []))
  3331 
  3332       val order = Graph.empty
  3333                   |> fold Graph.new_node variable_bounds
  3334                   |> fold add_deps variable_bounds
  3335                   |> Graph.strong_conn |> map the_single |> rev
  3336                   |> map_filter (AList.lookup (op =) variable_bounds)
  3337 
  3338       fun prepend_prem th tac
  3339         = tac THEN rtac (th RSN (2, @{thm mp})) i
  3340     in
  3341       fold prepend_prem order all_tac
  3342     end
  3343 
  3344   fun approximation_conv ctxt ct =
  3345     approximation_oracle (ProofContext.theory_of ctxt, Thm.term_of ct |> tap (tracing o Syntax.string_of_term ctxt));
  3346 
  3347   fun approximate ctxt t =
  3348     approximation_oracle (ProofContext.theory_of ctxt, t)
  3349     |> Thm.prop_of |> Logic.dest_equals |> snd;
  3350 
  3351   (* Should be in HOL.thy ? *)
  3352   fun gen_eval_tac conv ctxt = CONVERSION
  3353     (Object_Logic.judgment_conv (Conv.params_conv (~1) (K (Conv.concl_conv (~1) conv)) ctxt))
  3354     THEN' rtac TrueI
  3355 
  3356   val form_equations = @{thms interpret_form_equations};
  3357 
  3358   fun rewrite_interpret_form_tac ctxt prec splitting taylor i st = let
  3359       fun lookup_splitting (Free (name, typ))
  3360         = case AList.lookup (op =) splitting name
  3361           of SOME s => HOLogic.mk_number @{typ nat} s
  3362            | NONE => @{term "0 :: nat"}
  3363       val vs = nth (prems_of st) (i - 1)
  3364                |> Logic.strip_imp_concl
  3365                |> HOLogic.dest_Trueprop
  3366                |> Term.strip_comb |> snd |> List.last
  3367                |> HOLogic.dest_list
  3368       val p = prec
  3369               |> HOLogic.mk_number @{typ nat}
  3370               |> Thm.cterm_of (ProofContext.theory_of ctxt)
  3371     in case taylor
  3372     of NONE => let
  3373          val n = vs |> length
  3374                  |> HOLogic.mk_number @{typ nat}
  3375                  |> Thm.cterm_of (ProofContext.theory_of ctxt)
  3376          val s = vs
  3377                  |> map lookup_splitting
  3378                  |> HOLogic.mk_list @{typ nat}
  3379                  |> Thm.cterm_of (ProofContext.theory_of ctxt)
  3380        in
  3381          (rtac (Thm.instantiate ([], [(@{cpat "?n::nat"}, n),
  3382                                      (@{cpat "?prec::nat"}, p),
  3383                                      (@{cpat "?ss::nat list"}, s)])
  3384               @{thm "approx_form"}) i
  3385           THEN simp_tac @{simpset} i) st
  3386        end
  3387 
  3388      | SOME t => if length vs <> 1 then raise (TERM ("More than one variable used for taylor series expansion", [prop_of st]))
  3389        else let
  3390          val t = t
  3391               |> HOLogic.mk_number @{typ nat}
  3392               |> Thm.cterm_of (ProofContext.theory_of ctxt)
  3393          val s = vs |> map lookup_splitting |> hd
  3394               |> Thm.cterm_of (ProofContext.theory_of ctxt)
  3395        in
  3396          rtac (Thm.instantiate ([], [(@{cpat "?s::nat"}, s),
  3397                                      (@{cpat "?t::nat"}, t),
  3398                                      (@{cpat "?prec::nat"}, p)])
  3399               @{thm "approx_tse_form"}) i st
  3400        end
  3401     end
  3402 
  3403   (* copied from Tools/induct.ML should probably in args.ML *)
  3404   val free = Args.context -- Args.term >> (fn (_, Free (n, t)) => n | (ctxt, t) =>
  3405     error ("Bad free variable: " ^ Syntax.string_of_term ctxt t));
  3406 
  3407 *}
  3408 
  3409 lemma intervalE: "a \<le> x \<and> x \<le> b \<Longrightarrow> \<lbrakk> x \<in> { a .. b } \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P"
  3410   by auto
  3411 
  3412 lemma meta_eqE: "x \<equiv> a \<Longrightarrow> \<lbrakk> x = a \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P"
  3413   by auto
  3414 
  3415 method_setup approximation = {*
  3416   Scan.lift Parse.nat
  3417   --
  3418   Scan.optional (Scan.lift (Args.$$$ "splitting" |-- Args.colon)
  3419     |-- Parse.and_list' (free --| Scan.lift (Args.$$$ "=") -- Scan.lift Parse.nat)) []
  3420   --
  3421   Scan.option (Scan.lift (Args.$$$ "taylor" |-- Args.colon)
  3422     |-- (free |-- Scan.lift (Args.$$$ "=") |-- Scan.lift Parse.nat))
  3423   >>
  3424   (fn ((prec, splitting), taylor) => fn ctxt =>
  3425     SIMPLE_METHOD' (fn i =>
  3426       REPEAT (FIRST' [etac @{thm intervalE},
  3427                       etac @{thm meta_eqE},
  3428                       rtac @{thm impI}] i)
  3429       THEN Subgoal.FOCUS (fn {prems, ...} => reorder_bounds_tac prems i) @{context} i
  3430       THEN DETERM (TRY (filter_prems_tac (K false) i))
  3431       THEN DETERM (Reflection.genreify_tac ctxt form_equations NONE i)
  3432       THEN rewrite_interpret_form_tac ctxt prec splitting taylor i
  3433       THEN gen_eval_tac (approximation_conv ctxt) ctxt i))
  3434  *} "real number approximation"
  3435 
  3436 ML {*
  3437   fun calculated_subterms (@{const Trueprop} $ t) = calculated_subterms t
  3438     | calculated_subterms (@{const HOL.implies} $ _ $ t) = calculated_subterms t
  3439     | calculated_subterms (@{term "op <= :: real \<Rightarrow> real \<Rightarrow> bool"} $ t1 $ t2) = [t1, t2]
  3440     | calculated_subterms (@{term "op < :: real \<Rightarrow> real \<Rightarrow> bool"} $ t1 $ t2) = [t1, t2]
  3441     | calculated_subterms (@{term "op : :: real \<Rightarrow> real set \<Rightarrow> bool"} $ t1 $
  3442                            (@{term "atLeastAtMost :: real \<Rightarrow> real \<Rightarrow> real set"} $ t2 $ t3)) = [t1, t2, t3]
  3443     | calculated_subterms t = raise TERM ("calculated_subterms", [t])
  3444 
  3445   fun dest_interpret_form (@{const "interpret_form"} $ b $ xs) = (b, xs)
  3446     | dest_interpret_form t = raise TERM ("dest_interpret_form", [t])
  3447 
  3448   fun dest_interpret (@{const "interpret_floatarith"} $ b $ xs) = (b, xs)
  3449     | dest_interpret t = raise TERM ("dest_interpret", [t])
  3450 
  3451 
  3452   fun dest_float (@{const "Float"} $ m $ e) = (snd (HOLogic.dest_number m), snd (HOLogic.dest_number e))
  3453   fun dest_ivl (Const (@{const_name "Some"}, _) $
  3454                 (Const (@{const_name Pair}, _) $ u $ l)) = SOME (dest_float u, dest_float l)
  3455     | dest_ivl (Const (@{const_name "None"}, _)) = NONE
  3456     | dest_ivl t = raise TERM ("dest_result", [t])
  3457 
  3458   fun mk_approx' prec t = (@{const "approx'"}
  3459                          $ HOLogic.mk_number @{typ nat} prec
  3460                          $ t $ @{term "[] :: (float * float) option list"})
  3461 
  3462   fun mk_approx_form_eval prec t xs = (@{const "approx_form_eval"}
  3463                          $ HOLogic.mk_number @{typ nat} prec
  3464                          $ t $ xs)
  3465 
  3466   fun float2_float10 prec round_down (m, e) = (
  3467     let
  3468       val (m, e) = (if e < 0 then (m,e) else (m * Integer.pow e 2, 0))
  3469 
  3470       fun frac c p 0 digits cnt = (digits, cnt, 0)
  3471         | frac c 0 r digits cnt = (digits, cnt, r)
  3472         | frac c p r digits cnt = (let
  3473           val (d, r) = Integer.div_mod (r * 10) (Integer.pow (~e) 2)
  3474         in frac (c orelse d <> 0) (if d <> 0 orelse c then p - 1 else p) r
  3475                 (digits * 10 + d) (cnt + 1)
  3476         end)
  3477 
  3478       val sgn = Int.sign m
  3479       val m = abs m
  3480 
  3481       val round_down = (sgn = 1 andalso round_down) orelse
  3482                        (sgn = ~1 andalso not round_down)
  3483 
  3484       val (x, r) = Integer.div_mod m (Integer.pow (~e) 2)
  3485 
  3486       val p = ((if x = 0 then prec else prec - (IntInf.log2 x + 1)) * 3) div 10 + 1
  3487 
  3488       val (digits, e10, r) = if p > 0 then frac (x <> 0) p r 0 0 else (0,0,0)
  3489 
  3490       val digits = if round_down orelse r = 0 then digits else digits + 1
  3491 
  3492     in (sgn * (digits + x * (Integer.pow e10 10)), ~e10)
  3493     end)
  3494 
  3495   fun mk_result prec (SOME (l, u)) = (let
  3496       fun mk_float10 rnd x = (let val (m, e) = float2_float10 prec rnd x
  3497                          in if e = 0 then HOLogic.mk_number @{typ real} m
  3498                        else if e = 1 then @{term "divide :: real \<Rightarrow> real \<Rightarrow> real"} $
  3499                                           HOLogic.mk_number @{typ real} m $
  3500                                           @{term "10"}
  3501                                      else @{term "divide :: real \<Rightarrow> real \<Rightarrow> real"} $
  3502                                           HOLogic.mk_number @{typ real} m $
  3503                                           (@{term "power 10 :: nat \<Rightarrow> real"} $
  3504                                            HOLogic.mk_number @{typ nat} (~e)) end)
  3505       in @{term "atLeastAtMost :: real \<Rightarrow> real \<Rightarrow> real set"} $ mk_float10 true l $ mk_float10 false u end)
  3506     | mk_result prec NONE = @{term "UNIV :: real set"}
  3507 
  3508   fun realify t = let
  3509       val t = Logic.varify_global t
  3510       val m = map (fn (name, sort) => (name, @{typ real})) (Term.add_tvars t [])
  3511       val t = Term.subst_TVars m t
  3512     in t end
  3513 
  3514   fun converted_result t =
  3515           prop_of t
  3516        |> HOLogic.dest_Trueprop
  3517        |> HOLogic.dest_eq |> snd
  3518 
  3519   fun apply_tactic context term tactic = cterm_of context term
  3520     |> Goal.init
  3521     |> SINGLE tactic
  3522     |> the |> prems_of |> hd
  3523 
  3524   fun prepare_form context term = apply_tactic context term (
  3525       REPEAT (FIRST' [etac @{thm intervalE}, etac @{thm meta_eqE}, rtac @{thm impI}] 1)
  3526       THEN Subgoal.FOCUS (fn {prems, ...} => reorder_bounds_tac prems 1) @{context} 1
  3527       THEN DETERM (TRY (filter_prems_tac (K false) 1)))
  3528 
  3529   fun reify_form context term = apply_tactic context term
  3530      (Reflection.genreify_tac @{context} form_equations NONE 1)
  3531 
  3532   fun approx_form prec ctxt t =
  3533           realify t
  3534        |> prepare_form (ProofContext.theory_of ctxt)
  3535        |> (fn arith_term =>
  3536           reify_form (ProofContext.theory_of ctxt) arith_term
  3537        |> HOLogic.dest_Trueprop |> dest_interpret_form
  3538        |> (fn (data, xs) =>
  3539           mk_approx_form_eval prec data (HOLogic.mk_list @{typ "(float * float) option"}
  3540             (map (fn _ => @{term "None :: (float * float) option"}) (HOLogic.dest_list xs)))
  3541        |> approximate ctxt
  3542        |> HOLogic.dest_list
  3543        |> curry ListPair.zip (HOLogic.dest_list xs @ calculated_subterms arith_term)
  3544        |> map (fn (elem, s) => @{term "op : :: real \<Rightarrow> real set \<Rightarrow> bool"} $ elem $ mk_result prec (dest_ivl s))
  3545        |> foldr1 HOLogic.mk_conj))
  3546 
  3547   fun approx_arith prec ctxt t = realify t
  3548        |> Reflection.genreif ctxt form_equations
  3549        |> prop_of
  3550        |> HOLogic.dest_Trueprop
  3551        |> HOLogic.dest_eq |> snd
  3552        |> dest_interpret |> fst
  3553        |> mk_approx' prec
  3554        |> approximate ctxt
  3555        |> dest_ivl
  3556        |> mk_result prec
  3557 
  3558    fun approx prec ctxt t = if type_of t = @{typ prop} then approx_form prec ctxt t
  3559      else if type_of t = @{typ bool} then approx_form prec ctxt (@{const Trueprop} $ t)
  3560      else approx_arith prec ctxt t
  3561 *}
  3562 
  3563 setup {*
  3564   Value.add_evaluator ("approximate", approx 30)
  3565 *}
  3566 
  3567 end
  3568