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