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