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