(*  Title:       HOL/Complex.thy
    Author:      Jacques D. Fleuriot, 2001 University of Edinburgh
    Author:      Lawrence C Paulson, 2003/4
*)

section \<open>Complex Numbers: Rectangular and Polar Representations\<close>

theory Complex
imports Transcendental Real_Vector_Spaces
begin

text \<open>
  We use the \<^theory_text>\<open>codatatype\<close> command to define the type of complex numbers. This
  allows us to use \<^theory_text>\<open>primcorec\<close> to define complex functions by defining their
  real and imaginary result separately.
\<close>

codatatype complex = Complex (Re: real) (Im: real)

lemma complex_surj: "Complex (Re z) (Im z) = z"
  by (rule complex.collapse)

lemma complex_eqI [intro?]: "Re x = Re y \<Longrightarrow> Im x = Im y \<Longrightarrow> x = y"
  by (rule complex.expand) simp

lemma complex_eq_iff: "x = y \<longleftrightarrow> Re x = Re y \<and> Im x = Im y"
  by (auto intro: complex.expand)

subsection \<open>Addition and Subtraction\<close>

instantiation complex :: ab_group_add
begin

primcorec zero_complex
  where
    "Re 0 = 0"
  | "Im 0 = 0"

primcorec plus_complex
  where
    "Re (x + y) = Re x + Re y"
  | "Im (x + y) = Im x + Im y"

primcorec uminus_complex
  where
    "Re (- x) = - Re x"
  | "Im (- x) = - Im x"

primcorec minus_complex
  where
    "Re (x - y) = Re x - Re y"
  | "Im (x - y) = Im x - Im y"

instance
  by standard (simp_all add: complex_eq_iff)

end

subsection \<open>Multiplication and Division\<close>

instantiation complex :: field
begin

primcorec one_complex
  where
    "Re 1 = 1"
  | "Im 1 = 0"

primcorec times_complex
  where
    "Re (x * y) = Re x * Re y - Im x * Im y"
  | "Im (x * y) = Re x * Im y + Im x * Re y"

primcorec inverse_complex
  where
    "Re (inverse x) = Re x / ((Re x)\<^sup>2 + (Im x)\<^sup>2)"
  | "Im (inverse x) = - Im x / ((Re x)\<^sup>2 + (Im x)\<^sup>2)"

definition "x div y = x * inverse y" for x y :: complex

instance
  by standard
     (simp_all add: complex_eq_iff divide_complex_def
      distrib_left distrib_right right_diff_distrib left_diff_distrib
      power2_eq_square add_divide_distrib [symmetric])

end

lemma Re_divide: "Re (x / y) = (Re x * Re y + Im x * Im y) / ((Re y)\<^sup>2 + (Im y)\<^sup>2)"
  by (simp add: divide_complex_def add_divide_distrib)

lemma Im_divide: "Im (x / y) = (Im x * Re y - Re x * Im y) / ((Re y)\<^sup>2 + (Im y)\<^sup>2)"
  by (simp add: divide_complex_def diff_divide_distrib)

lemma Complex_divide:
    "(x / y) = Complex ((Re x * Re y + Im x * Im y) / ((Re y)\<^sup>2 + (Im y)\<^sup>2))
                       ((Im x * Re y - Re x * Im y) / ((Re y)\<^sup>2 + (Im y)\<^sup>2))"
  by (metis Im_divide Re_divide complex_surj)

lemma Re_power2: "Re (x ^ 2) = (Re x)^2 - (Im x)^2"
  by (simp add: power2_eq_square)

lemma Im_power2: "Im (x ^ 2) = 2 * Re x * Im x"
  by (simp add: power2_eq_square)

lemma Re_power_real [simp]: "Im x = 0 \<Longrightarrow> Re (x ^ n) = Re x ^ n "
  by (induct n) simp_all

lemma Im_power_real [simp]: "Im x = 0 \<Longrightarrow> Im (x ^ n) = 0"
  by (induct n) simp_all

subsection \<open>Scalar Multiplication\<close>

instantiation complex :: real_field
begin

primcorec scaleR_complex
  where
    "Re (scaleR r x) = r * Re x"
  | "Im (scaleR r x) = r * Im x"

instance
proof
  fix a b :: real and x y :: complex
  show "scaleR a (x + y) = scaleR a x + scaleR a y"
    by (simp add: complex_eq_iff distrib_left)
  show "scaleR (a + b) x = scaleR a x + scaleR b x"
    by (simp add: complex_eq_iff distrib_right)
  show "scaleR a (scaleR b x) = scaleR (a * b) x"
    by (simp add: complex_eq_iff mult.assoc)
  show "scaleR 1 x = x"
    by (simp add: complex_eq_iff)
  show "scaleR a x * y = scaleR a (x * y)"
    by (simp add: complex_eq_iff algebra_simps)
  show "x * scaleR a y = scaleR a (x * y)"
    by (simp add: complex_eq_iff algebra_simps)
qed

end

subsection \<open>Numerals, Arithmetic, and Embedding from R\<close>

declare [[coercion "of_real :: real \<Rightarrow> complex"]]
declare [[coercion "of_rat :: rat \<Rightarrow> complex"]]
declare [[coercion "of_int :: int \<Rightarrow> complex"]]
declare [[coercion "of_nat :: nat \<Rightarrow> complex"]]

abbreviation complex_of_nat::"nat \<Rightarrow> complex"
  where "complex_of_nat \<equiv> of_nat"

abbreviation complex_of_int::"int \<Rightarrow> complex"
  where "complex_of_int \<equiv> of_int"

abbreviation complex_of_rat::"rat \<Rightarrow> complex"
  where "complex_of_rat \<equiv> of_rat"

abbreviation complex_of_real :: "real \<Rightarrow> complex"
  where "complex_of_real \<equiv> of_real"

lemma complex_Re_of_nat [simp]: "Re (of_nat n) = of_nat n"
  by (induct n) simp_all

lemma complex_Im_of_nat [simp]: "Im (of_nat n) = 0"
  by (induct n) simp_all

lemma complex_Re_of_int [simp]: "Re (of_int z) = of_int z"
  by (cases z rule: int_diff_cases) simp

lemma complex_Im_of_int [simp]: "Im (of_int z) = 0"
  by (cases z rule: int_diff_cases) simp

lemma complex_Re_numeral [simp]: "Re (numeral v) = numeral v"
  using complex_Re_of_int [of "numeral v"] by simp

lemma complex_Im_numeral [simp]: "Im (numeral v) = 0"
  using complex_Im_of_int [of "numeral v"] by simp

lemma Re_complex_of_real [simp]: "Re (complex_of_real z) = z"
  by (simp add: of_real_def)

lemma Im_complex_of_real [simp]: "Im (complex_of_real z) = 0"
  by (simp add: of_real_def)

lemma Re_divide_numeral [simp]: "Re (z / numeral w) = Re z / numeral w"
  by (simp add: Re_divide sqr_conv_mult)

lemma Im_divide_numeral [simp]: "Im (z / numeral w) = Im z / numeral w"
  by (simp add: Im_divide sqr_conv_mult)

lemma Re_divide_of_nat [simp]: "Re (z / of_nat n) = Re z / of_nat n"
  by (cases n) (simp_all add: Re_divide field_split_simps power2_eq_square del: of_nat_Suc)

lemma Im_divide_of_nat [simp]: "Im (z / of_nat n) = Im z / of_nat n"
  by (cases n) (simp_all add: Im_divide field_split_simps power2_eq_square del: of_nat_Suc)

lemma Re_inverse [simp]: "r \<in> \<real> \<Longrightarrow> Re (inverse r) = inverse (Re r)"
  by (metis Re_complex_of_real Reals_cases of_real_inverse)

lemma Im_inverse [simp]: "r \<in> \<real> \<Longrightarrow> Im (inverse r) = 0"
  by (metis Im_complex_of_real Reals_cases of_real_inverse)

lemma of_real_Re [simp]: "z \<in> \<real> \<Longrightarrow> of_real (Re z) = z"
  by (auto simp: Reals_def)

lemma complex_Re_fact [simp]: "Re (fact n) = fact n"
proof -
  have "(fact n :: complex) = of_real (fact n)"
    by simp
  also have "Re \<dots> = fact n"
    by (subst Re_complex_of_real) simp_all
  finally show ?thesis .
qed

lemma surj_Re: "surj Re"
  by (metis Re_complex_of_real surj_def)

lemma surj_Im: "surj Im"
  by (metis complex.sel(2) surj_def)

lemma complex_Im_fact [simp]: "Im (fact n) = 0"
  by (metis complex_Im_of_nat of_nat_fact)

lemma Re_prod_Reals: "(\<And>x. x \<in> A \<Longrightarrow> f x \<in> \<real>) \<Longrightarrow> Re (prod f A) = prod (\<lambda>x. Re (f x)) A"
proof (induction A rule: infinite_finite_induct)
  case (insert x A)
  hence "Re (prod f (insert x A)) = Re (f x) * Re (prod f A) - Im (f x) * Im (prod f A)"
    by simp
  also from insert.prems have "f x \<in> \<real>" by simp
  hence "Im (f x) = 0" by (auto elim!: Reals_cases)
  also have "Re (prod f A) = (\<Prod>x\<in>A. Re (f x))"
    by (intro insert.IH insert.prems) auto
  finally show ?case using insert.hyps by simp
qed auto

subsection \<open>The Complex Number $i$\<close>

primcorec imaginary_unit :: complex  ("\<i>")
  where
    "Re \<i> = 0"
  | "Im \<i> = 1"

lemma Complex_eq: "Complex a b = a + \<i> * b"
  by (simp add: complex_eq_iff)

lemma complex_eq: "a = Re a + \<i> * Im a"
  by (simp add: complex_eq_iff)

lemma fun_complex_eq: "f = (\<lambda>x. Re (f x) + \<i> * Im (f x))"
  by (simp add: fun_eq_iff complex_eq)

lemma i_squared [simp]: "\<i> * \<i> = -1"
  by (simp add: complex_eq_iff)

lemma power2_i [simp]: "\<i>\<^sup>2 = -1"
  by (simp add: power2_eq_square)

lemma inverse_i [simp]: "inverse \<i> = - \<i>"
  by (rule inverse_unique) simp

lemma divide_i [simp]: "x / \<i> = - \<i> * x"
  by (simp add: divide_complex_def)

lemma complex_i_mult_minus [simp]: "\<i> * (\<i> * x) = - x"
  by (simp add: mult.assoc [symmetric])

lemma complex_i_not_zero [simp]: "\<i> \<noteq> 0"
  by (simp add: complex_eq_iff)

lemma complex_i_not_one [simp]: "\<i> \<noteq> 1"
  by (simp add: complex_eq_iff)

lemma complex_i_not_numeral [simp]: "\<i> \<noteq> numeral w"
  by (simp add: complex_eq_iff)

lemma complex_i_not_neg_numeral [simp]: "\<i> \<noteq> - numeral w"
  by (simp add: complex_eq_iff)

lemma complex_split_polar: "\<exists>r a. z = complex_of_real r * (cos a + \<i> * sin a)"
  by (simp add: complex_eq_iff polar_Ex)

lemma i_even_power [simp]: "\<i> ^ (n * 2) = (-1) ^ n"
  by (metis mult.commute power2_i power_mult)

lemma i_even_power' [simp]: "even n \<Longrightarrow> \<i> ^ n = (-1) ^ (n div 2)"
  by (metis dvd_mult_div_cancel power2_i power_mult)

lemma Re_i_times [simp]: "Re (\<i> * z) = - Im z"
  by simp

lemma Im_i_times [simp]: "Im (\<i> * z) = Re z"
  by simp

lemma i_times_eq_iff: "\<i> * w = z \<longleftrightarrow> w = - (\<i> * z)"
  by auto

lemma divide_numeral_i [simp]: "z / (numeral n * \<i>) = - (\<i> * z) / numeral n"
  by (metis divide_divide_eq_left divide_i mult.commute mult_minus_right)

lemma imaginary_eq_real_iff [simp]:
  assumes "y \<in> Reals" "x \<in> Reals"
  shows "\<i> * y = x \<longleftrightarrow> x=0 \<and> y=0"
  by (metis Im_complex_of_real Im_i_times assms mult_zero_right of_real_0 of_real_Re)

lemma real_eq_imaginary_iff [simp]:
  assumes "y \<in> Reals" "x \<in> Reals"
  shows "x = \<i> * y  \<longleftrightarrow> x=0 \<and> y=0"
    using assms imaginary_eq_real_iff by fastforce

subsection \<open>Vector Norm\<close>

instantiation complex :: real_normed_field
begin

definition "norm z = sqrt ((Re z)\<^sup>2 + (Im z)\<^sup>2)"

abbreviation cmod :: "complex \<Rightarrow> real"
  where "cmod \<equiv> norm"

definition complex_sgn_def: "sgn x = x /\<^sub>R cmod x"

definition dist_complex_def: "dist x y = cmod (x - y)"

definition uniformity_complex_def [code del]:
  "(uniformity :: (complex \<times> complex) filter) = (INF e\<in>{0 <..}. principal {(x, y). dist x y < e})"

definition open_complex_def [code del]:
  "open (U :: complex set) \<longleftrightarrow> (\<forall>x\<in>U. eventually (\<lambda>(x', y). x' = x \<longrightarrow> y \<in> U) uniformity)"

instance
proof
  fix r :: real and x y :: complex and S :: "complex set"
  show "(norm x = 0) = (x = 0)"
    by (simp add: norm_complex_def complex_eq_iff)
  show "norm (x + y) \<le> norm x + norm y"
    by (simp add: norm_complex_def complex_eq_iff real_sqrt_sum_squares_triangle_ineq)
  show "norm (scaleR r x) = \<bar>r\<bar> * norm x"
    by (simp add: norm_complex_def complex_eq_iff power_mult_distrib distrib_left [symmetric]
        real_sqrt_mult)
  show "norm (x * y) = norm x * norm y"
    by (simp add: norm_complex_def complex_eq_iff real_sqrt_mult [symmetric]
        power2_eq_square algebra_simps)
qed (rule complex_sgn_def dist_complex_def open_complex_def uniformity_complex_def)+

end

declare uniformity_Abort[where 'a = complex, code]

lemma norm_ii [simp]: "norm \<i> = 1"
  by (simp add: norm_complex_def)

lemma cmod_unit_one: "cmod (cos a + \<i> * sin a) = 1"
  by (simp add: norm_complex_def)

lemma cmod_complex_polar: "cmod (r * (cos a + \<i> * sin a)) = \<bar>r\<bar>"
  by (simp add: norm_mult cmod_unit_one)

lemma complex_Re_le_cmod: "Re x \<le> cmod x"
  unfolding norm_complex_def by (rule real_sqrt_sum_squares_ge1)

lemma complex_mod_minus_le_complex_mod: "- cmod x \<le> cmod x"
  by (rule order_trans [OF _ norm_ge_zero]) simp

lemma complex_mod_triangle_ineq2: "cmod (b + a) - cmod b \<le> cmod a"
  by (rule ord_le_eq_trans [OF norm_triangle_ineq2]) simp

lemma abs_Re_le_cmod: "\<bar>Re x\<bar> \<le> cmod x"
  by (simp add: norm_complex_def)

lemma abs_Im_le_cmod: "\<bar>Im x\<bar> \<le> cmod x"
  by (simp add: norm_complex_def)

lemma cmod_le: "cmod z \<le> \<bar>Re z\<bar> + \<bar>Im z\<bar>"
  using norm_complex_def sqrt_sum_squares_le_sum_abs by presburger

lemma cmod_eq_Re: "Im z = 0 \<Longrightarrow> cmod z = \<bar>Re z\<bar>"
  by (simp add: norm_complex_def)

lemma cmod_eq_Im: "Re z = 0 \<Longrightarrow> cmod z = \<bar>Im z\<bar>"
  by (simp add: norm_complex_def)

lemma cmod_power2: "(cmod z)\<^sup>2 = (Re z)\<^sup>2 + (Im z)\<^sup>2"
  by (simp add: norm_complex_def)

lemma cmod_plus_Re_le_0_iff: "cmod z + Re z \<le> 0 \<longleftrightarrow> Re z = - cmod z"
  using abs_Re_le_cmod[of z] by auto

lemma cmod_Re_le_iff: "Im x = Im y \<Longrightarrow> cmod x \<le> cmod y \<longleftrightarrow> \<bar>Re x\<bar> \<le> \<bar>Re y\<bar>"
  by (metis add.commute add_le_cancel_left norm_complex_def real_sqrt_abs real_sqrt_le_iff)

lemma cmod_Im_le_iff: "Re x = Re y \<Longrightarrow> cmod x \<le> cmod y \<longleftrightarrow> \<bar>Im x\<bar> \<le> \<bar>Im y\<bar>"
  by (metis add_le_cancel_left norm_complex_def real_sqrt_abs real_sqrt_le_iff)

lemma Im_eq_0: "\<bar>Re z\<bar> = cmod z \<Longrightarrow> Im z = 0"
  by (subst (asm) power_eq_iff_eq_base[symmetric, where n=2]) (auto simp add: norm_complex_def)

lemma abs_sqrt_wlog: "(\<And>x. x \<ge> 0 \<Longrightarrow> P x (x\<^sup>2)) \<Longrightarrow> P \<bar>x\<bar> (x\<^sup>2)"
  for x::"'a::linordered_idom"
  by (metis abs_ge_zero power2_abs)

lemma complex_abs_le_norm: "\<bar>Re z\<bar> + \<bar>Im z\<bar> \<le> sqrt 2 * norm z"
  unfolding norm_complex_def
  apply (rule abs_sqrt_wlog [where x="Re z"])
  apply (rule abs_sqrt_wlog [where x="Im z"])
  apply (rule power2_le_imp_le)
   apply (simp_all add: power2_sum add.commute sum_squares_bound real_sqrt_mult [symmetric])
  done

lemma complex_unit_circle: "z \<noteq> 0 \<Longrightarrow> (Re z / cmod z)\<^sup>2 + (Im z / cmod z)\<^sup>2 = 1"
  by (simp add: norm_complex_def complex_eq_iff power2_eq_square add_divide_distrib [symmetric])

text \<open>Properties of complex signum.\<close>

lemma sgn_eq: "sgn z = z / complex_of_real (cmod z)"
  by (simp add: sgn_div_norm divide_inverse scaleR_conv_of_real mult.commute)

lemma Re_sgn [simp]: "Re(sgn z) = Re(z)/cmod z"
  by (simp add: complex_sgn_def divide_inverse)

lemma Im_sgn [simp]: "Im(sgn z) = Im(z)/cmod z"
  by (simp add: complex_sgn_def divide_inverse)

subsection \<open>Absolute value\<close>

instantiation complex :: field_abs_sgn
begin

definition abs_complex :: "complex \<Rightarrow> complex"
  where "abs_complex = of_real \<circ> norm"

instance
  proof qed (auto simp add: abs_complex_def complex_sgn_def norm_divide norm_mult scaleR_conv_of_real field_simps)
end

subsection \<open>Completeness of the Complexes\<close>

lemma bounded_linear_Re: "bounded_linear Re"
  by (rule bounded_linear_intro [where K=1]) (simp_all add: norm_complex_def)

lemma bounded_linear_Im: "bounded_linear Im"
  by (rule bounded_linear_intro [where K=1]) (simp_all add: norm_complex_def)

lemmas Cauchy_Re = bounded_linear.Cauchy [OF bounded_linear_Re]
lemmas Cauchy_Im = bounded_linear.Cauchy [OF bounded_linear_Im]
lemmas tendsto_Re [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_Re]
lemmas tendsto_Im [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_Im]
lemmas isCont_Re [simp] = bounded_linear.isCont [OF bounded_linear_Re]
lemmas isCont_Im [simp] = bounded_linear.isCont [OF bounded_linear_Im]
lemmas continuous_Re [simp] = bounded_linear.continuous [OF bounded_linear_Re]
lemmas continuous_Im [simp] = bounded_linear.continuous [OF bounded_linear_Im]
lemmas continuous_on_Re [continuous_intros] = bounded_linear.continuous_on[OF bounded_linear_Re]
lemmas continuous_on_Im [continuous_intros] = bounded_linear.continuous_on[OF bounded_linear_Im]
lemmas has_derivative_Re [derivative_intros] = bounded_linear.has_derivative[OF bounded_linear_Re]
lemmas has_derivative_Im [derivative_intros] = bounded_linear.has_derivative[OF bounded_linear_Im]
lemmas sums_Re = bounded_linear.sums [OF bounded_linear_Re]
lemmas sums_Im = bounded_linear.sums [OF bounded_linear_Im]
lemmas Re_suminf = bounded_linear.suminf[OF bounded_linear_Re]
lemmas Im_suminf = bounded_linear.suminf[OF bounded_linear_Im]

lemma tendsto_Complex [tendsto_intros]:
  "(f \<longlongrightarrow> a) F \<Longrightarrow> (g \<longlongrightarrow> b) F \<Longrightarrow> ((\<lambda>x. Complex (f x) (g x)) \<longlongrightarrow> Complex a b) F"
  unfolding Complex_eq by (auto intro!: tendsto_intros)

lemma tendsto_complex_iff:
  "(f \<longlongrightarrow> x) F \<longleftrightarrow> (((\<lambda>x. Re (f x)) \<longlongrightarrow> Re x) F \<and> ((\<lambda>x. Im (f x)) \<longlongrightarrow> Im x) F)"
proof safe
  assume "((\<lambda>x. Re (f x)) \<longlongrightarrow> Re x) F" "((\<lambda>x. Im (f x)) \<longlongrightarrow> Im x) F"
  from tendsto_Complex[OF this] show "(f \<longlongrightarrow> x) F"
    unfolding complex.collapse .
qed (auto intro: tendsto_intros)

lemma continuous_complex_iff:
  "continuous F f \<longleftrightarrow> continuous F (\<lambda>x. Re (f x)) \<and> continuous F (\<lambda>x. Im (f x))"
  by (simp only: continuous_def tendsto_complex_iff)

lemma continuous_on_of_real_o_iff [simp]:
     "continuous_on S (\<lambda>x. complex_of_real (g x)) = continuous_on S g"
  using continuous_on_Re continuous_on_of_real  by fastforce

lemma continuous_on_of_real_id [simp]:
     "continuous_on S (of_real :: real \<Rightarrow> 'a::real_normed_algebra_1)"
  by (rule continuous_on_of_real [OF continuous_on_id])

lemma has_vector_derivative_complex_iff: "(f has_vector_derivative x) F \<longleftrightarrow>
    ((\<lambda>x. Re (f x)) has_field_derivative (Re x)) F \<and>
    ((\<lambda>x. Im (f x)) has_field_derivative (Im x)) F"
  by (simp add: has_vector_derivative_def has_field_derivative_def has_derivative_def
      tendsto_complex_iff algebra_simps bounded_linear_scaleR_left bounded_linear_mult_right)

lemma has_field_derivative_Re[derivative_intros]:
  "(f has_vector_derivative D) F \<Longrightarrow> ((\<lambda>x. Re (f x)) has_field_derivative (Re D)) F"
  unfolding has_vector_derivative_complex_iff by safe

lemma has_field_derivative_Im[derivative_intros]:
  "(f has_vector_derivative D) F \<Longrightarrow> ((\<lambda>x. Im (f x)) has_field_derivative (Im D)) F"
  unfolding has_vector_derivative_complex_iff by safe

instance complex :: banach
proof
  fix X :: "nat \<Rightarrow> complex"
  assume X: "Cauchy X"
  then have "(\<lambda>n. Complex (Re (X n)) (Im (X n))) \<longlonglongrightarrow>
    Complex (lim (\<lambda>n. Re (X n))) (lim (\<lambda>n. Im (X n)))"
    by (intro tendsto_Complex convergent_LIMSEQ_iff[THEN iffD1]
        Cauchy_convergent_iff[THEN iffD1] Cauchy_Re Cauchy_Im)
  then show "convergent X"
    unfolding complex.collapse by (rule convergentI)
qed

declare DERIV_power[where 'a=complex, unfolded of_nat_def[symmetric], derivative_intros]

subsection \<open>Complex Conjugation\<close>

primcorec cnj :: "complex \<Rightarrow> complex"
  where
    "Re (cnj z) = Re z"
  | "Im (cnj z) = - Im z"

lemma complex_cnj_cancel_iff [simp]: "cnj x = cnj y \<longleftrightarrow> x = y"
  by (simp add: complex_eq_iff)

lemma complex_cnj_cnj [simp]: "cnj (cnj z) = z"
  by (simp add: complex_eq_iff)

lemma in_image_cnj_iff: "z \<in> cnj ` A \<longleftrightarrow> cnj z \<in> A"
  by (metis complex_cnj_cnj image_iff)

lemma image_cnj_conv_vimage_cnj: "cnj ` A = cnj -` A"
  using in_image_cnj_iff by blast

lemma complex_cnj_zero [simp]: "cnj 0 = 0"
  by (simp add: complex_eq_iff)

lemma complex_cnj_zero_iff [iff]: "cnj z = 0 \<longleftrightarrow> z = 0"
  by (simp add: complex_eq_iff)

lemma complex_cnj_one_iff [simp]: "cnj z = 1 \<longleftrightarrow> z = 1"
  by (simp add: complex_eq_iff)

lemma complex_cnj_add [simp]: "cnj (x + y) = cnj x + cnj y"
  by (simp add: complex_eq_iff)

lemma cnj_sum [simp]: "cnj (sum f s) = (\<Sum>x\<in>s. cnj (f x))"
  by (induct s rule: infinite_finite_induct) auto

lemma complex_cnj_diff [simp]: "cnj (x - y) = cnj x - cnj y"
  by (simp add: complex_eq_iff)

lemma complex_cnj_minus [simp]: "cnj (- x) = - cnj x"
  by (simp add: complex_eq_iff)

lemma complex_cnj_one [simp]: "cnj 1 = 1"
  by (simp add: complex_eq_iff)

lemma complex_cnj_mult [simp]: "cnj (x * y) = cnj x * cnj y"
  by (simp add: complex_eq_iff)

lemma cnj_prod [simp]: "cnj (prod f s) = (\<Prod>x\<in>s. cnj (f x))"
  by (induct s rule: infinite_finite_induct) auto

lemma complex_cnj_inverse [simp]: "cnj (inverse x) = inverse (cnj x)"
  by (simp add: complex_eq_iff)

lemma complex_cnj_divide [simp]: "cnj (x / y) = cnj x / cnj y"
  by (simp add: divide_complex_def)

lemma complex_cnj_power [simp]: "cnj (x ^ n) = cnj x ^ n"
  by (induct n) simp_all

lemma complex_cnj_of_nat [simp]: "cnj (of_nat n) = of_nat n"
  by (simp add: complex_eq_iff)

lemma complex_cnj_of_int [simp]: "cnj (of_int z) = of_int z"
  by (simp add: complex_eq_iff)

lemma complex_cnj_numeral [simp]: "cnj (numeral w) = numeral w"
  by (simp add: complex_eq_iff)

lemma complex_cnj_neg_numeral [simp]: "cnj (- numeral w) = - numeral w"
  by (simp add: complex_eq_iff)

lemma complex_cnj_scaleR [simp]: "cnj (scaleR r x) = scaleR r (cnj x)"
  by (simp add: complex_eq_iff)

lemma complex_mod_cnj [simp]: "cmod (cnj z) = cmod z"
  by (simp add: norm_complex_def)

lemma complex_cnj_complex_of_real [simp]: "cnj (of_real x) = of_real x"
  by (simp add: complex_eq_iff)

lemma complex_cnj_i [simp]: "cnj \<i> = - \<i>"
  by (simp add: complex_eq_iff)

lemma complex_add_cnj: "z + cnj z = complex_of_real (2 * Re z)"
  by (simp add: complex_eq_iff)

lemma complex_diff_cnj: "z - cnj z = complex_of_real (2 * Im z) * \<i>"
  by (simp add: complex_eq_iff)

lemma Ints_cnj [intro]: "x \<in> \<int> \<Longrightarrow> cnj x \<in> \<int>"
  by (auto elim!: Ints_cases)

lemma cnj_in_Ints_iff [simp]: "cnj x \<in> \<int> \<longleftrightarrow> x \<in> \<int>"
  using Ints_cnj[of x] Ints_cnj[of "cnj x"] by auto

lemma complex_mult_cnj: "z * cnj z = complex_of_real ((Re z)\<^sup>2 + (Im z)\<^sup>2)"
  by (simp add: complex_eq_iff power2_eq_square)

lemma cnj_add_mult_eq_Re: "z * cnj w + cnj z * w = 2 * Re (z * cnj w)"
  by (rule complex_eqI) auto

lemma complex_mod_mult_cnj: "cmod (z * cnj z) = (cmod z)\<^sup>2"
  by (simp add: norm_mult power2_eq_square)

lemma complex_mod_sqrt_Re_mult_cnj: "cmod z = sqrt (Re (z * cnj z))"
  by (simp add: norm_complex_def power2_eq_square)

lemma complex_In_mult_cnj_zero [simp]: "Im (z * cnj z) = 0"
  by simp

lemma complex_cnj_fact [simp]: "cnj (fact n) = fact n"
  by (subst of_nat_fact [symmetric], subst complex_cnj_of_nat) simp

lemma complex_cnj_pochhammer [simp]: "cnj (pochhammer z n) = pochhammer (cnj z) n"
  by (induct n arbitrary: z) (simp_all add: pochhammer_rec)

lemma bounded_linear_cnj: "bounded_linear cnj"
  using complex_cnj_add complex_cnj_scaleR by (rule bounded_linear_intro [where K=1]) simp

lemma linear_cnj: "linear cnj"
  using bounded_linear.linear[OF bounded_linear_cnj] .

lemmas tendsto_cnj [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_cnj]
  and isCont_cnj [simp] = bounded_linear.isCont [OF bounded_linear_cnj]
  and continuous_cnj [simp, continuous_intros] = bounded_linear.continuous [OF bounded_linear_cnj]
  and continuous_on_cnj [simp, continuous_intros] = bounded_linear.continuous_on [OF bounded_linear_cnj]
  and has_derivative_cnj [simp, derivative_intros] = bounded_linear.has_derivative [OF bounded_linear_cnj]

lemma lim_cnj: "((\<lambda>x. cnj(f x)) \<longlongrightarrow> cnj l) F \<longleftrightarrow> (f \<longlongrightarrow> l) F"
  by (simp add: tendsto_iff dist_complex_def complex_cnj_diff [symmetric] del: complex_cnj_diff)

lemma sums_cnj: "((\<lambda>x. cnj(f x)) sums cnj l) \<longleftrightarrow> (f sums l)"
  by (simp add: sums_def lim_cnj cnj_sum [symmetric] del: cnj_sum)

lemma differentiable_cnj_iff:
  "(\<lambda>z. cnj (f z)) differentiable at x within A \<longleftrightarrow> f differentiable at x within A"
proof
  assume "(\<lambda>z. cnj (f z)) differentiable at x within A"
  then obtain D where "((\<lambda>z. cnj (f z)) has_derivative D) (at x within A)"
    by (auto simp: differentiable_def)
  from has_derivative_cnj[OF this] show "f differentiable at x within A"
    by (auto simp: differentiable_def)
next
  assume "f differentiable at x within A"
  then obtain D where "(f has_derivative D) (at x within A)"
    by (auto simp: differentiable_def)
  from has_derivative_cnj[OF this] show "(\<lambda>z. cnj (f z)) differentiable at x within A"
    by (auto simp: differentiable_def)
qed

lemma has_vector_derivative_cnj [derivative_intros]:
  assumes "(f has_vector_derivative f') (at z within A)"
  shows   "((\<lambda>z. cnj (f z)) has_vector_derivative cnj f') (at z within A)"
  using assms by (auto simp: has_vector_derivative_complex_iff intro: derivative_intros)

lemma has_field_derivative_cnj_cnj:
  assumes "(f has_field_derivative F) (at (cnj z))"
  shows   "((cnj \<circ> f \<circ> cnj) has_field_derivative cnj F) (at z)"
proof -
  have "cnj \<midarrow>0\<rightarrow> cnj 0"
    by (subst lim_cnj) auto
  also have "cnj 0 = 0"
    by simp
  finally have *: "filterlim cnj (at 0) (at 0)"
    by (auto simp: filterlim_at eventually_at_filter)
  have "(\<lambda>h. (f (cnj z + cnj h) - f (cnj z)) / cnj h) \<midarrow>0\<rightarrow> F"
    by (rule filterlim_compose[OF _ *]) (use assms in \<open>auto simp: DERIV_def\<close>)
  thus ?thesis
    by (subst (asm) lim_cnj [symmetric]) (simp add: DERIV_def)
qed

subsection \<open>Basic Lemmas\<close>

lemma complex_of_real_code[code_unfold]: "of_real = (\<lambda>x. Complex x 0)"
  by (intro ext, auto simp: complex_eq_iff)

lemma complex_eq_0: "z=0 \<longleftrightarrow> (Re z)\<^sup>2 + (Im z)\<^sup>2 = 0"
  by (metis zero_complex.sel complex_eqI sum_power2_eq_zero_iff)

lemma complex_neq_0: "z\<noteq>0 \<longleftrightarrow> (Re z)\<^sup>2 + (Im z)\<^sup>2 > 0"
  by (metis complex_eq_0 less_numeral_extra(3) sum_power2_gt_zero_iff)

lemma complex_norm_square: "of_real ((norm z)\<^sup>2) = z * cnj z"
  by (cases z)
    (auto simp: complex_eq_iff norm_complex_def power2_eq_square[symmetric] of_real_power[symmetric]
      simp del: of_real_power)

lemma complex_div_cnj: "a / b = (a * cnj b) / (norm b)\<^sup>2"
  using complex_norm_square by auto

lemma Re_complex_div_eq_0: "Re (a / b) = 0 \<longleftrightarrow> Re (a * cnj b) = 0"
  by (auto simp add: Re_divide)

lemma Im_complex_div_eq_0: "Im (a / b) = 0 \<longleftrightarrow> Im (a * cnj b) = 0"
  by (auto simp add: Im_divide)

lemma complex_div_gt_0: "(Re (a / b) > 0 \<longleftrightarrow> Re (a * cnj b) > 0) \<and> (Im (a / b) > 0 \<longleftrightarrow> Im (a * cnj b) > 0)"
proof (cases "b = 0")
  case True
  then show ?thesis by auto
next
  case False
  then have "0 < (Re b)\<^sup>2 + (Im b)\<^sup>2"
    by (simp add: complex_eq_iff sum_power2_gt_zero_iff)
  then show ?thesis
    by (simp add: Re_divide Im_divide zero_less_divide_iff)
qed

lemma Re_complex_div_gt_0: "Re (a / b) > 0 \<longleftrightarrow> Re (a * cnj b) > 0"
  and Im_complex_div_gt_0: "Im (a / b) > 0 \<longleftrightarrow> Im (a * cnj b) > 0"
  using complex_div_gt_0 by auto

lemma Re_complex_div_ge_0: "Re (a / b) \<ge> 0 \<longleftrightarrow> Re (a * cnj b) \<ge> 0"
  by (metis le_less Re_complex_div_eq_0 Re_complex_div_gt_0)

lemma Im_complex_div_ge_0: "Im (a / b) \<ge> 0 \<longleftrightarrow> Im (a * cnj b) \<ge> 0"
  by (metis Im_complex_div_eq_0 Im_complex_div_gt_0 le_less)

lemma Re_complex_div_lt_0: "Re (a / b) < 0 \<longleftrightarrow> Re (a * cnj b) < 0"
  by (metis less_asym neq_iff Re_complex_div_eq_0 Re_complex_div_gt_0)

lemma Im_complex_div_lt_0: "Im (a / b) < 0 \<longleftrightarrow> Im (a * cnj b) < 0"
  by (metis Im_complex_div_eq_0 Im_complex_div_gt_0 less_asym neq_iff)

lemma Re_complex_div_le_0: "Re (a / b) \<le> 0 \<longleftrightarrow> Re (a * cnj b) \<le> 0"
  by (metis not_le Re_complex_div_gt_0)

lemma Im_complex_div_le_0: "Im (a / b) \<le> 0 \<longleftrightarrow> Im (a * cnj b) \<le> 0"
  by (metis Im_complex_div_gt_0 not_le)

lemma Re_divide_of_real [simp]: "Re (z / of_real r) = Re z / r"
  by (simp add: Re_divide power2_eq_square)

lemma Im_divide_of_real [simp]: "Im (z / of_real r) = Im z / r"
  by (simp add: Im_divide power2_eq_square)

lemma Re_divide_Reals [simp]: "r \<in> \<real> \<Longrightarrow> Re (z / r) = Re z / Re r"
  by (metis Re_divide_of_real of_real_Re)

lemma Im_divide_Reals [simp]: "r \<in> \<real> \<Longrightarrow> Im (z / r) = Im z / Re r"
  by (metis Im_divide_of_real of_real_Re)

lemma Re_sum[simp]: "Re (sum f s) = (\<Sum>x\<in>s. Re (f x))"
  by (induct s rule: infinite_finite_induct) auto

lemma Im_sum[simp]: "Im (sum f s) = (\<Sum>x\<in>s. Im(f x))"
  by (induct s rule: infinite_finite_induct) auto

lemma sum_Re_le_cmod: "(\<Sum>i\<in>I. Re (z i)) \<le> cmod (\<Sum>i\<in>I. z i)"
  by (metis Re_sum complex_Re_le_cmod)

lemma sum_Im_le_cmod: "(\<Sum>i\<in>I. Im (z i)) \<le> cmod (\<Sum>i\<in>I. z i)"
  by (smt (verit, best) Im_sum abs_Im_le_cmod sum.cong)

lemma sums_complex_iff: "f sums x \<longleftrightarrow> ((\<lambda>x. Re (f x)) sums Re x) \<and> ((\<lambda>x. Im (f x)) sums Im x)"
  unfolding sums_def tendsto_complex_iff Im_sum Re_sum ..

lemma summable_complex_iff: "summable f \<longleftrightarrow> summable (\<lambda>x. Re (f x)) \<and>  summable (\<lambda>x. Im (f x))"
  unfolding summable_def sums_complex_iff[abs_def] by (metis complex.sel)

lemma summable_complex_of_real [simp]: "summable (\<lambda>n. complex_of_real (f n)) \<longleftrightarrow> summable f"
  unfolding summable_complex_iff by simp

lemma summable_Re: "summable f \<Longrightarrow> summable (\<lambda>x. Re (f x))"
  unfolding summable_complex_iff by blast

lemma summable_Im: "summable f \<Longrightarrow> summable (\<lambda>x. Im (f x))"
  unfolding summable_complex_iff by blast

lemma complex_is_Nat_iff: "z \<in> \<nat> \<longleftrightarrow> Im z = 0 \<and> (\<exists>i. Re z = of_nat i)"
  by (auto simp: Nats_def complex_eq_iff)

lemma complex_is_Int_iff: "z \<in> \<int> \<longleftrightarrow> Im z = 0 \<and> (\<exists>i. Re z = of_int i)"
  by (auto simp: Ints_def complex_eq_iff)

lemma complex_is_Real_iff: "z \<in> \<real> \<longleftrightarrow> Im z = 0"
  by (auto simp: Reals_def complex_eq_iff)

lemma Reals_cnj_iff: "z \<in> \<real> \<longleftrightarrow> cnj z = z"
  by (auto simp: complex_is_Real_iff complex_eq_iff)

lemma in_Reals_norm: "z \<in> \<real> \<Longrightarrow> norm z = \<bar>Re z\<bar>"
  by (simp add: complex_is_Real_iff norm_complex_def)

lemma Re_Reals_divide: "r \<in> \<real> \<Longrightarrow> Re (r / z) = Re r * Re z / (norm z)\<^sup>2"
  by (simp add: Re_divide complex_is_Real_iff cmod_power2)

lemma Im_Reals_divide: "r \<in> \<real> \<Longrightarrow> Im (r / z) = -Re r * Im z / (norm z)\<^sup>2"
  by (simp add: Im_divide complex_is_Real_iff cmod_power2)

lemma series_comparison_complex:
  fixes f:: "nat \<Rightarrow> 'a::banach"
  assumes sg: "summable g"
    and "\<And>n. g n \<in> \<real>" "\<And>n. Re (g n) \<ge> 0"
    and fg: "\<And>n. n \<ge> N \<Longrightarrow> norm(f n) \<le> norm(g n)"
  shows "summable f"
proof -
  have g: "\<And>n. cmod (g n) = Re (g n)"
    using assms by (metis abs_of_nonneg in_Reals_norm)
  show ?thesis
    by (metis fg g sg summable_comparison_test summable_complex_iff)
qed

subsection \<open>Polar Form for Complex Numbers\<close>

lemma complex_unimodular_polar:
  assumes "norm z = 1"
  obtains t where "0 \<le> t" "t < 2 * pi" "z = Complex (cos t) (sin t)"
  by (metis cmod_power2 one_power2 complex_surj sincos_total_2pi [of "Re z" "Im z"] assms)

subsubsection \<open>$\cos \theta + i \sin \theta$\<close>

primcorec cis :: "real \<Rightarrow> complex"
  where
    "Re (cis a) = cos a"
  | "Im (cis a) = sin a"

lemma cis_zero [simp]: "cis 0 = 1"
  by (simp add: complex_eq_iff)

lemma norm_cis [simp]: "norm (cis a) = 1"
  by (simp add: norm_complex_def)

lemma sgn_cis [simp]: "sgn (cis a) = cis a"
  by (simp add: sgn_div_norm)

lemma cis_2pi [simp]: "cis (2 * pi) = 1"
  by (simp add: cis.ctr complex_eq_iff)

lemma cis_neq_zero [simp]: "cis a \<noteq> 0"
  by (metis norm_cis norm_zero zero_neq_one)

lemma cis_cnj: "cnj (cis t) = cis (-t)"
  by (simp add: complex_eq_iff)

lemma cis_mult: "cis a * cis b = cis (a + b)"
  by (simp add: complex_eq_iff cos_add sin_add)

lemma DeMoivre: "(cis a) ^ n = cis (real n * a)"
  by (induct n) (simp_all add: algebra_simps cis_mult)

lemma cis_inverse [simp]: "inverse (cis a) = cis (- a)"
  by (simp add: complex_eq_iff)

lemma cis_divide: "cis a / cis b = cis (a - b)"
  by (simp add: divide_complex_def cis_mult)

lemma divide_conv_cnj: "norm z = 1 \<Longrightarrow> x / z = x * cnj z"
  by (metis complex_div_cnj div_by_1 mult_1 of_real_1 power2_eq_square)

lemma i_not_in_Reals [simp, intro]: "\<i> \<notin> \<real>"
  by (auto simp: complex_is_Real_iff)

lemma powr_power_complex: "z \<noteq> 0 \<or> n \<noteq> 0 \<Longrightarrow> (z powr u :: complex) ^ n = z powr (of_nat n * u)"
  by (induction n) (auto simp: algebra_simps powr_add)

lemma cos_n_Re_cis_pow_n: "cos (real n * a) = Re (cis a ^ n)"
  by (auto simp add: DeMoivre)

lemma sin_n_Im_cis_pow_n: "sin (real n * a) = Im (cis a ^ n)"
  by (auto simp add: DeMoivre)

lemma cis_pi [simp]: "cis pi = -1"
  by (simp add: complex_eq_iff)

lemma cis_pi_half[simp]: "cis (pi / 2) = \<i>"
  by (simp add: cis.ctr complex_eq_iff)

lemma cis_minus_pi_half[simp]: "cis (-(pi / 2)) = -\<i>"
  by (simp add: cis.ctr complex_eq_iff)

lemma cis_multiple_2pi[simp]: "n \<in> \<int> \<Longrightarrow> cis (2 * pi * n) = 1"
  by (auto elim!: Ints_cases simp: cis.ctr one_complex.ctr)

lemma minus_cis: "-cis x = cis (x + pi)"
  by (simp flip: cis_mult)

lemma minus_cis': "-cis x = cis (x - pi)"
  by (simp flip: cis_divide)

subsubsection \<open>$r(\cos \theta + i \sin \theta)$\<close>

definition rcis :: "real \<Rightarrow> real \<Rightarrow> complex"
  where "rcis r a = complex_of_real r * cis a"

lemma Re_rcis [simp]: "Re(rcis r a) = r * cos a"
  by (simp add: rcis_def)

lemma Im_rcis [simp]: "Im(rcis r a) = r * sin a"
  by (simp add: rcis_def)

lemma rcis_Ex: "\<exists>r a. z = rcis r a"
  by (simp add: complex_eq_iff polar_Ex)

lemma complex_mod_rcis [simp]: "cmod (rcis r a) = \<bar>r\<bar>"
  by (simp add: rcis_def norm_mult)

lemma cis_rcis_eq: "cis a = rcis 1 a"
  by (simp add: rcis_def)

lemma rcis_mult: "rcis r1 a * rcis r2 b = rcis (r1 * r2) (a + b)"
  by (simp add: rcis_def cis_mult)

lemma rcis_zero_mod [simp]: "rcis 0 a = 0"
  by (simp add: rcis_def)

lemma rcis_zero_arg [simp]: "rcis r 0 = complex_of_real r"
  by (simp add: rcis_def)

lemma rcis_eq_zero_iff [simp]: "rcis r a = 0 \<longleftrightarrow> r = 0"
  by (simp add: rcis_def)

lemma DeMoivre2: "(rcis r a) ^ n = rcis (r ^ n) (real n * a)"
  by (simp add: rcis_def power_mult_distrib DeMoivre)

lemma rcis_inverse: "inverse(rcis r a) = rcis (1 / r) (- a)"
  by (simp add: divide_inverse rcis_def)

lemma rcis_divide: "rcis r1 a / rcis r2 b = rcis (r1 / r2) (a - b)"
  by (simp add: rcis_def cis_divide [symmetric])

subsubsection \<open>Complex exponential\<close>

lemma exp_Reals_eq:
  assumes "z \<in> \<real>"
  shows   "exp z = of_real (exp (Re z))"
  using assms by (auto elim!: Reals_cases simp: exp_of_real)

lemma cis_conv_exp: "cis b = exp (\<i> * b)"
proof -
  have "(\<i> * complex_of_real b) ^ n /\<^sub>R fact n =
      of_real (cos_coeff n * b^n) + \<i> * of_real (sin_coeff n * b^n)"
    for n :: nat
  proof -
    have "\<i> ^ n = fact n *\<^sub>R (cos_coeff n + \<i> * sin_coeff n)"
      by (induct n)
        (simp_all add: sin_coeff_Suc cos_coeff_Suc complex_eq_iff Re_divide Im_divide field_simps
          power2_eq_square add_nonneg_eq_0_iff)
    then show ?thesis
      by (simp add: field_simps)
  qed
  then show ?thesis
    using sin_converges [of b] cos_converges [of b]
    by (auto simp add: Complex_eq cis.ctr exp_def simp del: of_real_mult
        intro!: sums_unique sums_add sums_mult sums_of_real)
qed

lemma exp_eq_polar: "exp z = exp (Re z) * cis (Im z)"
  unfolding cis_conv_exp exp_of_real [symmetric] mult_exp_exp
  by (cases z) (simp add: Complex_eq)

lemma Re_exp: "Re (exp z) = exp (Re z) * cos (Im z)"
  unfolding exp_eq_polar by simp

lemma Im_exp: "Im (exp z) = exp (Re z) * sin (Im z)"
  unfolding exp_eq_polar by simp

lemma norm_cos_sin [simp]: "norm (Complex (cos t) (sin t)) = 1"
  by (simp add: norm_complex_def)

lemma norm_exp_eq_Re [simp]: "norm (exp z) = exp (Re z)"
  by (simp add: cis.code cmod_complex_polar exp_eq_polar Complex_eq)

lemma complex_exp_exists: "\<exists>a r. z = complex_of_real r * exp a"
  using cis_conv_exp rcis_Ex rcis_def by force

lemma exp_pi_i [simp]: "exp (of_real pi * \<i>) = -1"
  by (metis cis_conv_exp cis_pi mult.commute)

lemma exp_pi_i' [simp]: "exp (\<i> * of_real pi) = -1"
  using cis_conv_exp cis_pi by auto

lemma exp_two_pi_i [simp]: "exp (2 * of_real pi * \<i>) = 1"
  by (simp add: exp_eq_polar complex_eq_iff)

lemma exp_two_pi_i' [simp]: "exp (\<i> * (of_real pi * 2)) = 1"
  by (metis exp_two_pi_i mult.commute)

lemma continuous_on_cis [continuous_intros]:
  "continuous_on A f \<Longrightarrow> continuous_on A (\<lambda>x. cis (f x))"
  by (auto simp: cis_conv_exp intro!: continuous_intros)

lemma tendsto_exp_0_Re_at_bot: "(exp \<longlongrightarrow> 0) (filtercomap Re at_bot)"
proof -
  have "((\<lambda>z. cmod (exp z)) \<longlongrightarrow> 0) (filtercomap Re at_bot)"
    by (auto intro!: filterlim_filtercomapI exp_at_bot)
  thus ?thesis
    using tendsto_norm_zero_iff by blast
qed

lemma filterlim_exp_at_infinity_Re_at_top: "filterlim exp at_infinity (filtercomap Re at_top)"
proof -
  have "filterlim (\<lambda>z. norm (exp z)) at_top (filtercomap Re at_top)"
    by (auto intro!: filterlim_filtercomapI exp_at_top)
  thus ?thesis
    using filterlim_norm_at_top_imp_at_infinity by blast
qed

subsubsection \<open>Complex argument\<close>

definition Arg :: "complex \<Rightarrow> real"
  where "Arg z = (if z = 0 then 0 else (SOME a. sgn z = cis a \<and> - pi < a \<and> a \<le> pi))"

lemma Arg_zero: "Arg 0 = 0"
  by (simp add: Arg_def)

lemma cis_Arg_unique:
  assumes "sgn z = cis x" and "-pi < x" and "x \<le> pi"
  shows "Arg z = x"
proof -
  from assms have "z \<noteq> 0" by auto
  have "(SOME a. sgn z = cis a \<and> -pi < a \<and> a \<le> pi) = x"
  proof
    fix a
    define d where "d = a - x"
    assume a: "sgn z = cis a \<and> - pi < a \<and> a \<le> pi"
    from a assms have "- (2*pi) < d \<and> d < 2*pi"
      unfolding d_def by simp
    moreover
    from a assms have "cos a = cos x" and "sin a = sin x"
      by (simp_all add: complex_eq_iff)
    then have cos: "cos d = 1"
      by (simp add: d_def cos_diff)
    moreover from cos have "sin d = 0"
      by (rule cos_one_sin_zero)
    ultimately have "d = 0"
      by (auto simp: sin_zero_iff elim!: evenE dest!: less_2_cases)
    then show "a = x"
      by (simp add: d_def)
  qed (simp add: assms del: Re_sgn Im_sgn)
  with \<open>z \<noteq> 0\<close> show "Arg z = x"
    by (simp add: Arg_def)
qed

lemma Arg_correct:
  assumes "z \<noteq> 0"
  shows "sgn z = cis (Arg z) \<and> -pi < Arg z \<and> Arg z \<le> pi"
proof (simp add: Arg_def assms, rule someI_ex)
  obtain r a where z: "z = rcis r a"
    using rcis_Ex by fast
  with assms have "r \<noteq> 0" by auto
  define b where "b = (if 0 < r then a else a + pi)"
  have b: "sgn z = cis b"
    using \<open>r \<noteq> 0\<close> by (simp add: z b_def rcis_def of_real_def sgn_scaleR sgn_if complex_eq_iff)
  have cis_2pi_nat: "cis (2 * pi * real_of_nat n) = 1" for n
    by (induct n) (simp_all add: distrib_left cis_mult [symmetric] complex_eq_iff)
  have cis_2pi_int: "cis (2 * pi * real_of_int x) = 1" for x
    by (cases x rule: int_diff_cases)
      (simp add: right_diff_distrib cis_divide [symmetric] cis_2pi_nat)
  define c where "c = b - 2 * pi * of_int \<lceil>(b - pi) / (2 * pi)\<rceil>"
  have "sgn z = cis c"
    by (simp add: b c_def cis_divide [symmetric] cis_2pi_int)
  moreover have "- pi < c \<and> c \<le> pi"
    using ceiling_correct [of "(b - pi) / (2*pi)"]
    by (simp add: c_def less_divide_eq divide_le_eq algebra_simps del: le_of_int_ceiling)
  ultimately show "\<exists>a. sgn z = cis a \<and> -pi < a \<and> a \<le> pi"
    by fast
qed

lemma Arg_bounded: "- pi < Arg z \<and> Arg z \<le> pi"
  by (cases "z = 0") (simp_all add: Arg_zero Arg_correct)

lemma cis_Arg: "z \<noteq> 0 \<Longrightarrow> cis (Arg z) = sgn z"
  by (simp add: Arg_correct)

lemma rcis_cmod_Arg: "rcis (cmod z) (Arg z) = z"
  by (cases "z = 0") (simp_all add: rcis_def cis_Arg sgn_div_norm of_real_def)

lemma rcis_cnj:
  shows "cnj a = rcis (cmod a) (- Arg a)"
  by (metis cis_cnj complex_cnj_complex_of_real complex_cnj_mult rcis_cmod_Arg rcis_def)

lemma cos_Arg_i_mult_zero [simp]: "y \<noteq> 0 \<Longrightarrow> Re y = 0 \<Longrightarrow> cos (Arg y) = 0"
  using cis_Arg [of y] by (simp add: complex_eq_iff)

lemma Arg_ii [simp]: "Arg \<i> = pi/2"
  by (rule cis_Arg_unique; simp add: sgn_eq)

lemma Arg_minus_ii [simp]: "Arg (-\<i>) = -pi/2"
proof (rule cis_Arg_unique)
  show "sgn (- \<i>) = cis (- pi / 2)"
    by (simp add: sgn_eq)
  show "- pi / 2 \<le> pi"
    using pi_not_less_zero by linarith
qed auto

lemma cos_Arg: "z \<noteq> 0 \<Longrightarrow> cos (Arg z) = Re z / norm z"
  by (metis Re_sgn cis.sel(1) cis_Arg)

lemma sin_Arg: "z \<noteq> 0 \<Longrightarrow> sin (Arg z) = Im z / norm z"
  by (metis Im_sgn cis.sel(2) cis_Arg)

subsection \<open>Complex n-th roots\<close>

lemma bij_betw_roots_unity:
  assumes "n > 0"
  shows   "bij_betw (\<lambda>k. cis (2 * pi * real k / real n)) {..<n} {z. z ^ n = 1}"
    (is "bij_betw ?f _ _")
  unfolding bij_betw_def
proof (intro conjI)
  show inj: "inj_on ?f {..<n}" unfolding inj_on_def
  proof (safe, goal_cases)
    case (1 k l)
    hence kl: "k < n" "l < n" by simp_all
    from 1 have "1 = ?f k / ?f l" by simp
    also have "\<dots> = cis (2*pi*(real k - real l)/n)"
      using assms by (simp add: field_simps cis_divide)
    finally have "cos (2*pi*(real k - real l) / n) = 1"
      by (simp add: complex_eq_iff)
    then obtain m :: int where "2 * pi * (real k - real l) / real n = real_of_int m * 2 * pi"
      by (subst (asm) cos_one_2pi_int) blast
    hence "real_of_int (int k - int l) = real_of_int (m * int n)"
      unfolding of_int_diff of_int_mult using assms
      by (simp add: nonzero_divide_eq_eq)
    also note of_int_eq_iff
    finally have *: "abs m * n = abs (int k - int l)" by (simp add: abs_mult)
    also have "\<dots> < int n" using kl by linarith
    finally have "m = 0" using assms by simp
    with * show "k = l" by simp
  qed

  have subset: "?f ` {..<n} \<subseteq> {z. z ^ n = 1}"
  proof safe
    fix k :: nat
    have "cis (2 * pi * real k / real n) ^ n = cis (2 * pi) ^ k"
      using assms by (simp add: DeMoivre mult_ac)
    also have "cis (2 * pi) = 1" by (simp add: complex_eq_iff)
    finally show "?f k ^ n = 1" by simp
  qed

  have "n = card {..<n}" by simp
  also from assms and subset have "\<dots> \<le> card {z::complex. z ^ n = 1}"
    by (intro card_inj_on_le[OF inj]) (auto simp: finite_roots_unity)
  finally have card: "card {z::complex. z ^ n = 1} = n"
    using assms by (intro antisym card_roots_unity) auto

  have "card (?f ` {..<n}) = card {z::complex. z ^ n = 1}"
    using card inj by (subst card_image) auto
  with subset and assms show "?f ` {..<n} = {z::complex. z ^ n = 1}"
    by (intro card_subset_eq finite_roots_unity) auto
qed

lemma card_roots_unity_eq:
  assumes "n > 0"
  shows   "card {z::complex. z ^ n = 1} = n"
  using bij_betw_same_card [OF bij_betw_roots_unity [OF assms]] by simp

lemma bij_betw_nth_root_unity:
  fixes c :: complex and n :: nat
  assumes c: "c \<noteq> 0" and n: "n > 0"
  defines "c' \<equiv> root n (norm c) * cis (Arg c / n)"
  shows "bij_betw (\<lambda>z. c' * z) {z. z ^ n = 1} {z. z ^ n = c}"
proof -
  have "c' ^ n = of_real (root n (norm c) ^ n) * cis (Arg c)"
    unfolding of_real_power using n by (simp add: c'_def power_mult_distrib DeMoivre)
  also from n have "root n (norm c) ^ n = norm c" by simp
  also from c have "of_real \<dots> * cis (Arg c) = c" by (simp add: cis_Arg Complex.sgn_eq)
  finally have [simp]: "c' ^ n = c" .

  show ?thesis unfolding bij_betw_def inj_on_def
  proof safe
    fix z :: complex assume "z ^ n = 1"
    hence "(c' * z) ^ n = c' ^ n" by (simp add: power_mult_distrib)
    also have "c' ^ n = of_real (root n (norm c) ^ n) * cis (Arg c)"
      unfolding of_real_power using n by (simp add: c'_def power_mult_distrib DeMoivre)
    also from n have "root n (norm c) ^ n = norm c" by simp
    also from c have "\<dots> * cis (Arg c) = c" by (simp add: cis_Arg Complex.sgn_eq)
    finally show "(c' * z) ^ n = c" .
  next
    fix z assume z: "c = z ^ n"
    define z' where "z' = z / c'"
    from c and n have "c' \<noteq> 0" by (auto simp: c'_def)
    with n c have "z = c' * z'" and "z' ^ n = 1"
      by (auto simp: z'_def power_divide z)
    thus "z \<in> (\<lambda>z. c' * z) ` {z. z ^ n = 1}" by blast
  qed (insert c n, auto simp: c'_def)
qed

lemma finite_nth_roots [intro]:
  assumes "n > 0"
  shows   "finite {z::complex. z ^ n = c}"
proof (cases "c = 0")
  case True
  with assms have "{z::complex. z ^ n = c} = {0}" by auto
  thus ?thesis by simp
next
  case False
  from assms have "finite {z::complex. z ^ n = 1}" by (intro finite_roots_unity) simp_all
  also have "?this \<longleftrightarrow> ?thesis"
    by (rule bij_betw_finite, rule bij_betw_nth_root_unity) fact+
  finally show ?thesis .
qed

lemma card_nth_roots:
  assumes "c \<noteq> 0" "n > 0"
  shows   "card {z::complex. z ^ n = c} = n"
proof -
  have "card {z. z ^ n = c} = card {z::complex. z ^ n = 1}"
    by (rule sym, rule bij_betw_same_card, rule bij_betw_nth_root_unity) fact+
  also have "\<dots> = n" by (rule card_roots_unity_eq) fact+
  finally show ?thesis .
qed

lemma sum_roots_unity:
  assumes "n > 1"
  shows   "\<Sum>{z::complex. z ^ n = 1} = 0"
proof -
  define \<omega> where "\<omega> = cis (2 * pi / real n)"
  have [simp]: "\<omega> \<noteq> 1"
  proof
    assume "\<omega> = 1"
    with assms obtain k :: int where "2 * pi / real n = 2 * pi * of_int k"
      by (auto simp: \<omega>_def complex_eq_iff cos_one_2pi_int)
    with assms have "real n * of_int k = 1" by (simp add: field_simps)
    also have "real n * of_int k = of_int (int n * k)" by simp
    also have "1 = (of_int 1 :: real)" by simp
    also note of_int_eq_iff
    finally show False using assms by (auto simp: zmult_eq_1_iff)
  qed

  have "(\<Sum>z | z ^ n = 1. z :: complex) = (\<Sum>k<n. cis (2 * pi * real k / real n))"
    using assms by (intro sum.reindex_bij_betw [symmetric] bij_betw_roots_unity) auto
  also have "\<dots> = (\<Sum>k<n. \<omega> ^ k)"
    by (intro sum.cong refl) (auto simp: \<omega>_def DeMoivre mult_ac)
  also have "\<dots> = (\<omega> ^ n - 1) / (\<omega> - 1)"
    by (subst geometric_sum) auto
  also have "\<omega> ^ n - 1 = cis (2 * pi) - 1" using assms by (auto simp: \<omega>_def DeMoivre)
  also have "\<dots> = 0" by (simp add: complex_eq_iff)
  finally show ?thesis by simp
qed

lemma sum_nth_roots:
  assumes "n > 1"
  shows   "\<Sum>{z::complex. z ^ n = c} = 0"
proof (cases "c = 0")
  case True
  with assms have "{z::complex. z ^ n = c} = {0}" by auto
  also have "\<Sum>\<dots> = 0" by simp
  finally show ?thesis .
next
  case False
  define c' where "c' = root n (norm c) * cis (Arg c / n)"
  from False and assms have "(\<Sum>{z. z ^ n = c}) = (\<Sum>z | z ^ n = 1. c' * z)"
    by (subst sum.reindex_bij_betw [OF bij_betw_nth_root_unity, symmetric])
       (auto simp: sum_distrib_left finite_roots_unity c'_def)
  also from assms have "\<dots> = 0"
    by (simp add: sum_distrib_left [symmetric] sum_roots_unity)
  finally show ?thesis .
qed

subsection \<open>Square root of complex numbers\<close>

primcorec csqrt :: "complex \<Rightarrow> complex"
  where
    "Re (csqrt z) = sqrt ((cmod z + Re z) / 2)"
  | "Im (csqrt z) = (if Im z = 0 then 1 else sgn (Im z)) * sqrt ((cmod z - Re z) / 2)"

lemma csqrt_of_real_nonneg [simp]: "Im x = 0 \<Longrightarrow> Re x \<ge> 0 \<Longrightarrow> csqrt x = sqrt (Re x)"
  by (simp add: complex_eq_iff norm_complex_def)

lemma csqrt_of_real_nonpos [simp]: "Im x = 0 \<Longrightarrow> Re x \<le> 0 \<Longrightarrow> csqrt x = \<i> * sqrt \<bar>Re x\<bar>"
  by (simp add: complex_eq_iff norm_complex_def)

lemma of_real_sqrt: "x \<ge> 0 \<Longrightarrow> of_real (sqrt x) = csqrt (of_real x)"
  by (simp add: complex_eq_iff norm_complex_def)

lemma csqrt_0 [simp]: "csqrt 0 = 0"
  by simp

lemma csqrt_1 [simp]: "csqrt 1 = 1"
  by simp

lemma csqrt_ii [simp]: "csqrt \<i> = (1 + \<i>) / sqrt 2"
  by (simp add: complex_eq_iff Re_divide Im_divide real_sqrt_divide real_div_sqrt)

lemma power2_csqrt[simp,algebra]: "(csqrt z)\<^sup>2 = z"
proof (cases "Im z = 0")
  case True
  then show ?thesis
    using real_sqrt_pow2[of "Re z"] real_sqrt_pow2[of "- Re z"]
    by (cases "0::real" "Re z" rule: linorder_cases)
      (simp_all add: complex_eq_iff Re_power2 Im_power2 power2_eq_square cmod_eq_Re)
next
  case False
  moreover have "cmod z * cmod z - Re z * Re z = Im z * Im z"
    by (simp add: norm_complex_def power2_eq_square)
  moreover have "\<bar>Re z\<bar> \<le> cmod z"
    by (simp add: norm_complex_def)
  ultimately show ?thesis
    by (simp add: Re_power2 Im_power2 complex_eq_iff real_sgn_eq
        field_simps real_sqrt_mult[symmetric] real_sqrt_divide)
qed

lemma csqrt_power_even:
  assumes "even n"
  shows   "csqrt z ^ n = z ^ (n div 2)"
  by (metis assms dvd_mult_div_cancel power2_csqrt power_mult)

lemma norm_csqrt [simp]: "norm (csqrt z) = sqrt (norm z)"
  by (metis abs_of_nonneg norm_ge_zero norm_mult power2_csqrt power2_eq_square real_sqrt_abs)

lemma csqrt_eq_0 [simp]: "csqrt z = 0 \<longleftrightarrow> z = 0"
  by auto (metis power2_csqrt power_eq_0_iff)

lemma csqrt_eq_1 [simp]: "csqrt z = 1 \<longleftrightarrow> z = 1"
  by auto (metis power2_csqrt power2_eq_1_iff)

lemma csqrt_principal: "0 < Re (csqrt z) \<or> Re (csqrt z) = 0 \<and> 0 \<le> Im (csqrt z)"
  by (auto simp add: not_less cmod_plus_Re_le_0_iff Im_eq_0)

lemma Re_csqrt: "0 \<le> Re (csqrt z)"
  by (metis csqrt_principal le_less)

lemma csqrt_square:
  assumes "0 < Re b \<or> (Re b = 0 \<and> 0 \<le> Im b)"
  shows "csqrt (b^2) = b"
proof -
  have "csqrt (b^2) = b \<or> csqrt (b^2) = - b"
    by (simp add: power2_eq_iff[symmetric])
  moreover have "csqrt (b^2) \<noteq> -b \<or> b = 0"
    using csqrt_principal[of "b ^ 2"] assms
    by (intro disjCI notI) (auto simp: complex_eq_iff)
  ultimately show ?thesis
    by auto
qed

lemma csqrt_unique: "w\<^sup>2 = z \<Longrightarrow> 0 < Re w \<or> Re w = 0 \<and> 0 \<le> Im w \<Longrightarrow> csqrt z = w"
  by (auto simp: csqrt_square)

lemma csqrt_minus [simp]:
  assumes "Im x < 0 \<or> (Im x = 0 \<and> 0 \<le> Re x)"
  shows "csqrt (- x) = \<i> * csqrt x"
proof -
  have "csqrt ((\<i> * csqrt x)^2) = \<i> * csqrt x"
  proof (rule csqrt_square)
    have "Im (csqrt x) \<le> 0"
      using assms by (auto simp add: cmod_eq_Re mult_le_0_iff field_simps complex_Re_le_cmod)
    then show "0 < Re (\<i> * csqrt x) \<or> Re (\<i> * csqrt x) = 0 \<and> 0 \<le> Im (\<i> * csqrt x)"
      by (auto simp add: Re_csqrt simp del: csqrt.simps)
  qed
  also have "(\<i> * csqrt x)^2 = - x"
    by (simp add: power_mult_distrib)
  finally show ?thesis .
qed

text \<open>Legacy theorem names\<close>

lemmas cmod_def = norm_complex_def

lemma legacy_Complex_simps:
  shows Complex_eq_0: "Complex a b = 0 \<longleftrightarrow> a = 0 \<and> b = 0"
    and complex_add: "Complex a b + Complex c d = Complex (a + c) (b + d)"
    and complex_minus: "- (Complex a b) = Complex (- a) (- b)"
    and complex_diff: "Complex a b - Complex c d = Complex (a - c) (b - d)"
    and Complex_eq_1: "Complex a b = 1 \<longleftrightarrow> a = 1 \<and> b = 0"
    and Complex_eq_neg_1: "Complex a b = - 1 \<longleftrightarrow> a = - 1 \<and> b = 0"
    and complex_mult: "Complex a b * Complex c d = Complex (a * c - b * d) (a * d + b * c)"
    and complex_inverse: "inverse (Complex a b) = Complex (a / (a\<^sup>2 + b\<^sup>2)) (- b / (a\<^sup>2 + b\<^sup>2))"
    and Complex_eq_numeral: "Complex a b = numeral w \<longleftrightarrow> a = numeral w \<and> b = 0"
    and Complex_eq_neg_numeral: "Complex a b = - numeral w \<longleftrightarrow> a = - numeral w \<and> b = 0"
    and complex_scaleR: "scaleR r (Complex a b) = Complex (r * a) (r * b)"
    and Complex_eq_i: "Complex x y = \<i> \<longleftrightarrow> x = 0 \<and> y = 1"
    and i_mult_Complex: "\<i> * Complex a b = Complex (- b) a"
    and Complex_mult_i: "Complex a b * \<i> = Complex (- b) a"
    and i_complex_of_real: "\<i> * complex_of_real r = Complex 0 r"
    and complex_of_real_i: "complex_of_real r * \<i> = Complex 0 r"
    and Complex_add_complex_of_real: "Complex x y + complex_of_real r = Complex (x+r) y"
    and complex_of_real_add_Complex: "complex_of_real r + Complex x y = Complex (r+x) y"
    and Complex_mult_complex_of_real: "Complex x y * complex_of_real r = Complex (x*r) (y*r)"
    and complex_of_real_mult_Complex: "complex_of_real r * Complex x y = Complex (r*x) (r*y)"
    and complex_eq_cancel_iff2: "(Complex x y = complex_of_real xa) = (x = xa \<and> y = 0)"
    and complex_cnj: "cnj (Complex a b) = Complex a (- b)"
    and Complex_sum': "sum (\<lambda>x. Complex (f x) 0) s = Complex (sum f s) 0"
    and Complex_sum: "Complex (sum f s) 0 = sum (\<lambda>x. Complex (f x) 0) s"
    and complex_of_real_def: "complex_of_real r = Complex r 0"
    and complex_norm: "cmod (Complex x y) = sqrt (x\<^sup>2 + y\<^sup>2)"
  by (simp_all add: norm_complex_def field_simps complex_eq_iff Re_divide Im_divide)

lemma Complex_in_Reals: "Complex x 0 \<in> \<real>"
  by (metis Reals_of_real complex_of_real_def)

text \<open>Express a complex number as a linear combination of two others, not collinear with the origin\<close>
lemma complex_axes:
  assumes "Im (y/x) \<noteq> 0"
  obtains a b where "z = of_real a * x + of_real b * y"
proof -
  define dd where "dd \<equiv> Re y * Im x -  Im y * Re x"
  define a where "a = (Im z * Re y - Re z * Im y) / dd"
  define b where "b = (Re z * Im x - Im z * Re x) / dd"
  have "dd \<noteq> 0"
    using assms by (auto simp: dd_def Im_complex_div_eq_0)
  have "a * Re x + b * Re y = Re z"
    using \<open>dd \<noteq> 0\<close>
    apply (simp add: a_def b_def field_simps)
    by (metis dd_def diff_add_cancel distrib_right mult.assoc mult.commute)
  moreover have "a * Im x + b * Im y = Im z"
    using \<open>dd \<noteq> 0\<close>
    apply (simp add: a_def b_def field_simps)
    by (metis (no_types) dd_def diff_add_cancel distrib_right mult.assoc mult.commute)
  ultimately have "z = of_real a * x + of_real b * y"
    by (simp add: complex_eqI)
  then show ?thesis using that by simp
qed

end


theory Chapter2
imports Main
begin

text{*
\section*{Chapter 2}

\exercise
Use the \textbf{value} command to evaluate the following expressions:
*}
value "bool"
value "True"
value "1 + (2::nat)"
value "1 + (2::int)"
value "1 - (2::nat)"
value "1 - (2::int)"
value "[a,b] @ [c,d]"
value "(+) (1::nat) 1"
value "(=) 1 (1::nat)"

fun "conj" :: "bool \<Rightarrow> bool \<Rightarrow> bool" where
"conj True True = True" |
"conj _ _ = False"

text{*
\endexercise
\exercise
Recall the definition of our own addition function on @{typ nat}:
*}

fun "add" :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
"add 0 n = n" |
"add (Suc m) n = Suc(add m n)"

text{*
Prove that @{const add} is associative and commutative.
You will need additional lemmas.
*}

lemma "add (add m n) p = add m (add n p)"
proof (induction m)
  case 0
  have "add (add 0 n) p = add n p" by simp
  also have "add n p = add 0 (add n p)" by simp
  finally show "add (add 0 n) p = add 0 (add n p)" by simp
next
  case ind : (Suc m)
  have "add (add (Suc m) n) p = add (Suc (add m n)) p" by simp
  also have "add (Suc (add m n)) p = Suc (add (add m n) p)" by simp
  also have "Suc (add (add m n) p) = Suc (add m (add n p))" by (simp add : ind.IH)
  also have "Suc (add m (add n p)) = add (Suc m) (add n p)" by simp
  finally show "add (add (Suc m) n) p = add (Suc m) (add n p)" by simp
qed
lemma add_comm_aux_1 [simp] : "add m 0 = m"
  apply (induction m)
  apply (auto)
  done

lemma add_comm_aux_2 [simp] : "add m (Suc n) = Suc (add m n)"
  apply (induction m)
   apply (auto)
  done

lemma add_comm: "add m n = add n m"
  apply (induction m)
   apply (auto)
done

lemma add_comm_isar : "add m n = add n m"
proof (induction m)
  case 0
  have "add 0 n = n" by simp
  also have "add n 0 = n"
  proof (induction n)
    case 0
    show "add 0 0 = 0" by simp
  next
    case ind: (Suc n)
    have "add (Suc n) 0 = Suc (add n 0)" by simp
    also have "Suc (add n 0) = Suc n" by (simp add : ind.IH)
    finally show "add (Suc n) 0 = Suc n" by simp
  qed
  then show "add 0 n = add n 0" by simp
next
  case ind: (Suc m)
  have "add m n = add n m" by (simp add : ind.IH)
  also have "add (Suc m) n = Suc (add m n)" by simp
  have "add n (Suc m) = Suc (add n m)" by simp
  finally show "add (Suc m) n = add n (Suc m)" by (simp add : ind.IH)
qed

text{* Define a recursive function *}
fun "double" :: "nat \<Rightarrow> nat" where
  "double 0 = 0"|
  "double (Suc n) = Suc (Suc (double n))"

text{* and prove that *}

lemma double_add: "double m = add m m"
  apply (induction m)
   apply (auto)
  done

lemma double_add_isar : "double m = add m m"
proof (induction m)
  case 0
  show "double 0 = add 0 0" by simp
next
  case ind : (Suc m)
  have "double (Suc m) = Suc (Suc (double m))" by simp
  also have "Suc (Suc (double m)) = Suc (Suc (add m m))" by (simp add : ind.IH)
  also have "Suc (Suc (add m m)) = Suc (add (Suc m) m)" by simp
  also have "Suc (add (Suc m) m) = add (Suc m) (Suc m)" by simp
  finally show "double (Suc m) = add (Suc m) (Suc m)" by simp
qed

text{*
\endexercise

\exercise
Define a function that counts the number of occurrences of
an element in a list:
*}

fun count :: "'a list \<Rightarrow> 'a \<Rightarrow> nat" where
  "count [] _ = 0"
| "count (x#xs) y = ((if x = y then 1 else 0) + count xs y)"

value "count [1,2,5,5] (5::nat)"

text {*
Test your definition of @{term count} on some examples.
Prove the following inequality:
*}

theorem "count xs x \<le> length xs"
  apply(induction xs)
   apply auto
  done
find_theorems count
thm count.simps
theorem "count xs y \<le> length xs"
proof (induction xs)
  case Nil
  have "count [] y = 0" by simp
  also have "0 \<le> length []" by simp
  finally show "count [] y \<le> length []" by auto
next
  case ind : (Cons x xs)
  have "count (x # xs) y \<le> 1 + count xs y" by simp
  also have "1 + count xs y \<le> 1 + length xs" using ind.IH by simp
  also have "1 + length xs = length (x # xs)" by simp
  finally show "count (x # xs) y \<le> length (x # xs)" by simp
qed

text{*
\endexercise
\exercise
Define a function @{text snoc} that appends an element to the end of a list.
Do not use the existing append operator @{text "@"} for lists.
*}

fun snoc :: "'a list \<Rightarrow> 'a \<Rightarrow> 'a list" where
  "snoc [] x = [x]"
| "snoc (y#ys) x = y # (snoc ys x)"

value "snoc [1,2,3::nat] 4"

text {*
Convince yourself on some test cases that your definition
of @{term snoc} behaves as expected.
With the help of @{text snoc} define a recursive function @{text reverse}
that reverses a list. Do not use the predefined function @{const rev}.
*}

fun reverse :: "'a list \<Rightarrow> 'a list" where
  "reverse [] = []"
| "reverse (x#xs) = snoc (reverse xs) x"

value "reverse [1,2,3::nat]"

text {*
Prove the following theorem. You will need an additional lemma.
*}

lemma rev_snoc : "reverse (snoc xs a) = a # (reverse xs)"
  apply (induction xs)
   apply (auto)
  done

lemma rev_snoc_isar : "reverse (snoc xs a) = a # (reverse xs)"
proof (induction xs)
  case Nil
  have "reverse (snoc [] a) = [a]" by simp
  also have "a # (reverse []) = [a]" by simp
  finally show "reverse (snoc [] a) = a # (reverse [])" by simp
next
  case ind : (Cons x xs)
  show "reverse (snoc (x # xs) a) = a # reverse (x # xs)" by (simp add : ind.IH)
qed

theorem "reverse (reverse xs) = xs"
  apply (induction xs)
   apply (simp_all add : rev_snoc )
  done

theorem "reverse (reverse xs) = xs"
proof (induction xs)
  case Nil
  show ?case by simp
next
  case ind : (Cons a xs)
  have "reverse (reverse (a # xs)) = reverse (snoc (reverse xs) a)" by simp
  also have "... = a # (reverse (reverse xs))" by (simp add : rev_snoc)
  also have "... = a # xs" by (simp add : ind.IH)
  finally show "reverse (reverse (a # xs)) = a # xs" by auto
qed

text{*
\endexercise

\exercise
The aim of this exercise is to prove the summation formula
\[ \sum_{i=0}^{n}i = \frac{n(n+1)}{2} \]
Define a recursive function @{text "sum_upto n = 0 + ... + n"}:
*}

fun sum_upto :: "nat \<Rightarrow> nat" where
  "sum_upto 0 = 0"
| "sum_upto (Suc n) = Suc n + sum_upto n"

value "sum_upto 3"

text {*
Now prove the summation formula by induction on @{text "n"}.
First, write a clear but informal proof by hand following the examples
in the main text. Then prove the same property in Isabelle:
*}

lemma "sum_upto n = n * (n+1) div 2"
  apply (induction n)
   apply (simp_all)
  done
lemma "sum_upto n = n * (n+1) div 2"
proof (induction n)
  case 0
  have "sum_upto (0::nat) = 0" by simp
  also have "(0::nat) * ((0 + 1) div 2) = 0" by simp
  finally show "sum_upto 0 = 0 * (0 + 1) div 2" by simp
next
  case ind : (Suc n)
  have "sum_upto (Suc n) = (Suc n) + sum_upto n" by simp
  also have "Suc n + sum_upto n = Suc n + (n * (n + 1) div 2)" by (simp add : ind.IH)
  finally show "sum_upto (Suc n) = Suc n * (Suc n + 1) div 2" by simp
qed

fun itrev :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list" where
  "itrev [] ys = ys"
| "itrev (x # xs) ys = itrev xs (x # ys)"

value "itrev [1,2,3::nat] []"

lemma "itrev xs [] = rev xs"
  apply (induction xs)
  sorry

lemma "itrev xs [x] = (itrev xs []) @ [x]"
  apply (induction xs)
  apply (auto)
  sorry

lemma "itrev xs ys = (rev xs) @ ys"
proof (induction xs arbitrary : ys)
  case Nil
  show "itrev [] ys = rev [] @ ys" by simp
next
  case ind : (Cons a xs)
  have "itrev (a # xs) ys = itrev xs (a # ys)" by simp
  also have "itrev xs (a # ys) = (rev xs) @ (a # ys)" by (auto simp add : ind.IH)
  also have "(rev xs) @ (a # ys) = rev (a # xs) @ ys" by simp
  finally show "itrev (a # xs) ys = rev (a # xs) @ ys" by simp
qed

lemma "itrev xs ys = (rev xs) @ ys"
  apply (induction xs arbitrary : ys)
   apply (auto)
  done

text{*
\endexercise

\exercise
Starting from the type @{text "'a tree"} defined in the text, define
a function that collects all values in a tree in a list, in any order,
without removing duplicates.
*}
datatype 'a tree = Tip | Node "'a tree" 'a "'a tree"

fun contents :: "'a tree \<Rightarrow> 'a list" where
  "contents Tip = []"
| "contents (Node T1 x T2) = x # (contents T1) @ (contents T2)"

value "contents t1"

text{*
Then define a function that sums up all values in a tree of natural numbers
*}

fun sum_tree :: "nat tree \<Rightarrow> nat" where
  "sum_tree Tip = 0"
| "sum_tree (Node T1 x T2) = x + (sum_tree T1) + (sum_tree T2)"

fun sum_list :: "nat list \<Rightarrow> nat" where
  "sum_list [] = 0"
| "sum_list (x#xs) = x + sum_list xs"

value "sum_tree t1"
value "sum_list [1,2,3]"

text{* and prove *}

lemma sum_list_aux : "sum_list (l1 @ l2) = sum_list l1 + sum_list l2"
  apply (induction l1)
   apply (auto)
  done

lemma "sum_tree t = sum_list (contents t)"
  apply (induction t rule : sum_tree.induct)
   apply (auto simp add : sum_list_aux)
  done

lemma "sum_tree t = sum_list (contents t)"
proof (induction t)
  case Tip
  have "sum_tree Tip = 0" by simp
  also have "Chapter2.sum_list (contents Tip) = 0" by simp
  finally show ?case by simp
next
  case ind : (Node T1 x T2)
  have "sum_tree (Node T1 x T2) = x + (sum_tree T1) + (sum_tree T2)" by simp
  also have "... = x + (Chapter2.sum_list (contents T1)) + (Chapter2.sum_list (contents T2))"
    by (simp add : ind.IH)
  also have "... = Chapter2.sum_list (contents (Node T1 x T2))" by (simp add : sum_list_aux)
  finally show "sum_tree (Node T1 x T2) = Chapter2.sum_list (contents (Node T1 x T2))" by simp
qed

text{*
\endexercise

\exercise
Define a new type @{text "'a tree2"} of binary trees where values are also
stored in the leaves of the tree.  Also reformulate the
@{text mirror} function accordingly. Define two functions *}

datatype 'a tree2 = Tip2 'a | Node2 "'a tree2" 'a "'a tree2"

fun "mirror2" :: "'a tree2 \<Rightarrow> 'a tree2" where
  "mirror2 (Tip2 x) = Tip2 x"
| "mirror2 (Node2 (t1 :: 'a tree2) x t2) = Node2 (mirror2 t2) x (mirror2 t1)"

fun pre_order :: "'a tree2 \<Rightarrow> 'a list" where
  "pre_order (Tip2 x) = [x]"
| "pre_order (Node2 t1 x t2) = (pre_order t1) @ [x] @ (pre_order t2)"

fun post_order :: "'a tree2 \<Rightarrow> 'a list" where
  "post_order (Tip2 x) = [x]"
| "post_order (Node2 t1 x t2) = (post_order t2) @ [x] @ (post_order t1)"

text{*
that traverse a tree and collect all stored values in the respective order in
a list. Prove *}

lemma "pre_order (mirror2 t) = post_order t"
  apply (induction t)
   apply (auto)
  done

lemma "pre_order (mirror2 t) = post_order t"
proof (induction t)
  case Tip2
  show ?case by simp
next
  case ind : (Node2 t1 x t2)
  show ?case by (auto simp add : ind.IH)
qed

text{*
\endexercise

\exercise
Define a recursive function
*}

fun intersperse :: "'a \<Rightarrow> 'a list \<Rightarrow> 'a list" where
  "intersperse _ [] = []"
| "intersperse a (x # xs) = [x,a] @ (intersperse a xs)"

text{*
such that @{text "intersperse a [x\<^sub>1, ..., x\<^sub>n] = [x\<^sub>1, a, x\<^sub>2, a, ..., a, x\<^sub>n]"}.
Prove
*}

lemma "map f (intersperse a xs) = intersperse (f a) (map f xs)"
  apply (induction xs)
   apply (auto)
  done

lemma "map f (intersperse a xs) = intersperse (f a) (map f xs)"
proof (induction xs)
  case Nil
  show ?case by simp
next
  case ind : (Cons a xs)
  show ?case by (auto simp add : ind.IH)
qed

text{*
\endexercise

\exercise
Write a tail-recursive variant of the @{text add} function on @{typ nat}:
*}

fun itadd :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
  "itadd 0 n = n"
| "itadd (Suc m) n = itadd m (Suc n)"

text{*
Tail-recursive means that in the recursive case, @{const itadd} needs to call
itself directly: \mbox{@{term"itadd (Suc m) n"}} @{text"= itadd \<dots>"}.
Prove
*}

lemma "itadd m n = add m n"
  by (induction m arbitrary : n) auto

lemma "itadd m n = add m n"
proof (induction m arbitrary : n)
  case 0
  show ?case by simp
next
  case ind : (Suc m)
  have "itadd (Suc m) n = itadd m (Suc n)" by simp
  also have "... = add m (Suc n)" by (simp add : ind.IH)
  also have "add m (Suc n) = add (Suc m) n" by simp
  finally show "itadd (Suc m) n = add (Suc m) n" by simp
qed

text{*
\endexercise

\exercise\label{exe:tree0}
Define a datatype @{text tree0} of binary tree skeletons which do not store
any information, neither in the inner nodes nor in the leaves.
Define a function that counts the number of all nodes (inner nodes and leaves)
in such a tree:
*}

datatype tree0 = Tip | Node "tree0" "tree0"

fun nodes :: "tree0 \<Rightarrow> nat" where
  "nodes Tip = 1"
| "nodes (Node t1 t2) = 1 + nodes t1 + nodes t2"

text {*
Consider the following recursive function:
*}

fun explode :: "nat \<Rightarrow> tree0 \<Rightarrow> tree0" where
"explode 0 t = t" |
"explode (Suc n) t = explode n (Node t t)"

text {*
Experiment how @{text explode} influences the size of a binary tree
and find an equation expressing the size of a tree after exploding it
(\noquotes{@{term [source] "nodes (explode n t)"}}) as a function
of @{term "nodes t"} and @{text n}. Prove your equation.
You may use the usual arithmetic operations including the exponentiation
operator ``@{text"^"}''. For example, \noquotes{@{prop [source] "2 ^ 2 = 4"}}.

Hint: simplifying with the list of theorems @{thm[source] algebra_simps}
takes care of common algebraic properties of the arithmetic operators.
\endexercise
*}

lemma "nodes (explode n t) = 2^n * (nodes t) + 2^n - 1"
  apply (induction n arbitrary : t)
   apply (auto simp add : algebra_simps)
  done

lemma "nodes (explode n t) = 2^n * (nodes t) + 2^n - 1"
proof (induction n arbitrary : t)
  case 0
  show ?case by simp
next
  case ind : (Suc n)
  show ?case by (simp add : algebra_simps ind.IH)
qed

text{*

\exercise
Define arithmetic expressions in one variable over integers (type @{typ int})
as a data type:
*}

datatype exp = Var | Const int | Add exp exp | Mult exp exp

text{*
Define a function @{text eval} that evaluates an expression at some value:
*}

fun eval :: "exp \<Rightarrow> int \<Rightarrow> int" where
  "eval Var a = a"
| "eval (Const k) _ = k"
| "eval (Add e1 e2) a = (eval e1) a + (eval e2) a"
| "eval (Mult e1 e2) a = (eval e1) a * (eval e2) a"

value "eval (Add (Mult (Const 2) Var) (Const 3)) 5 = 2*i+3"

text{*
For example, @{prop"eval (Add (Mult (Const 2) Var) (Const 3)) i = 2*i+3"}.

A polynomial can be represented as a list of coefficients, starting with
the constant. For example, @{term "[4, 2, -1, 3::int]"} represents the
polynomial $4 + 2x - x^2 + 3x^3$.
Define a function @{text evalp} that evaluates a polynomial at a given value:
*}

fun evalp :: "int list \<Rightarrow> int \<Rightarrow> int" where
  "evalp [] _ = 0"
| "evalp (c#cs) k = c + k * (evalp cs k)"

value "evalp [4,2,-1,3] 1"

text{*
Define a function @{text coeffs} that transforms an expression into a polynomial.
This will require auxiliary functions.
*}

fun add_intlist_intlist :: "int list \<Rightarrow> int list \<Rightarrow> int list" where
  "add_intlist_intlist [] ys = ys"
| "add_intlist_intlist xs [] = xs"
| "add_intlist_intlist (x#xs) (y#ys) = (x+y)#(add_intlist_intlist xs ys)"

fun mult_int_intlist :: "int \<Rightarrow> int list \<Rightarrow> int list" where
  "mult_int_intlist _ [] = []"
| "mult_int_intlist x (y#ys) = (x*y) # (mult_int_intlist x ys)"

fun mult_intlist_intlist :: "int list \<Rightarrow> int list \<Rightarrow> int list" where
  "mult_intlist_intlist [] ys = ys"
| "mult_intlist_intlist (x#xs) ys =
   add_intlist_intlist (mult_int_intlist x ys) (0#(mult_intlist_intlist xs ys))"

fun coeffs :: "exp \<Rightarrow> int list" where
  "coeffs Var = [0,1]"
| "coeffs (Const c) = [c]"
| "coeffs (Add e1 e2) = add_intlist_intlist (coeffs e1) (coeffs e2)"
| "coeffs (Mult e1 e2) = mult_intlist_intlist (coeffs e1) (coeffs e2)"

text{*
Prove that @{text coeffs} preserves the value of the expression:
*}

lemma "evalp (add_intlist_intlist xs ys) x = evalp xs x + evalp ys x"
  apply (induction xs arbitrary:x)
   apply (simp_all)
  apply (induction ys)
  apply (simp_all)

theorem evalp_coeffs: "evalp (coeffs e) x = eval e x"
  apply (induction e arbitrary:x)
  apply (simp_all)

theorem evalp_coeffs: "evalp (coeffs e) x = eval e x"
proof (induction e arbitrary:x)
  case Var
  show ?case by simp
next
  case (Const x)
  show ?case by simp
next
  case ind_add : (Add e1 e2)
  have "evalp (coeffs (Add e1 e2)) x = evalp (add_intlist_intlist (coeffs e1) (coeffs e2)) x" by simp

text{*
Hint: consider the hint in Exercise~\ref{exe:tree0}.
\endexercise
*}

end


(*  Title       : NthRoot.thy
    Author      : Jacques D. Fleuriot
    Copyright   : 1998  University of Cambridge
    Conversion to Isar and new proofs by Lawrence C Paulson, 2004
*)

section {* Nth Roots of Real Numbers *}

theory NthRoot
imports Deriv
begin

lemma abs_sgn_eq: "abs (sgn x :: real) = (if x = 0 then 0 else 1)"
  by (simp add: sgn_real_def)

lemma inverse_sgn: "sgn (inverse a) = inverse (sgn a :: real)"
  by (simp add: sgn_real_def)

lemma power_eq_iff_eq_base:
  fixes a b :: "_ :: linordered_semidom"
  shows "0 < n \<Longrightarrow> 0 \<le> a \<Longrightarrow> 0 \<le> b \<Longrightarrow> a ^ n = b ^ n \<longleftrightarrow> a = b"
  using power_eq_imp_eq_base[of a n b] by auto

subsection {* Existence of Nth Root *}

text {* Existence follows from the Intermediate Value Theorem *}

lemma realpow_pos_nth:
  assumes n: "0 < n"
  assumes a: "0 < a"
  shows "\<exists>r>0. r ^ n = (a::real)"
proof -
  have "\<exists>r\<ge>0. r \<le> (max 1 a) \<and> r ^ n = a"
  proof (rule IVT)
    show "0 ^ n \<le> a" using n a by (simp add: power_0_left)
    show "0 \<le> max 1 a" by simp
    from n have n1: "1 \<le> n" by simp
    have "a \<le> max 1 a ^ 1" by simp
    also have "max 1 a ^ 1 \<le> max 1 a ^ n"
      using n1 by (rule power_increasing, simp)
    finally show "a \<le> max 1 a ^ n" .
    show "\<forall>r. 0 \<le> r \<and> r \<le> max 1 a \<longrightarrow> isCont (\<lambda>x. x ^ n) r"
      by simp
  qed
  then obtain r where r: "0 \<le> r \<and> r ^ n = a" by fast
  with n a have "r \<noteq> 0" by (auto simp add: power_0_left)
  with r have "0 < r \<and> r ^ n = a" by simp
  thus ?thesis ..
qed

(* Used by Integration/RealRandVar.thy in AFP *)
lemma realpow_pos_nth2: "(0::real) < a \<Longrightarrow> \<exists>r>0. r ^ Suc n = a"
by (blast intro: realpow_pos_nth)

text {* Uniqueness of nth positive root *}

lemma realpow_pos_nth_unique: "\<lbrakk>0 < n; 0 < a\<rbrakk> \<Longrightarrow> \<exists>!r. 0 < r \<and> r ^ n = (a::real)"
  by (auto intro!: realpow_pos_nth simp: power_eq_iff_eq_base)

subsection {* Nth Root *}

text {* We define roots of negative reals such that
  @{term "root n (- x) = - root n x"}. This allows
  us to omit side conditions from many theorems. *}

lemma inj_sgn_power: assumes "0 < n" shows "inj (\<lambda>y. sgn y * \<bar>y\<bar>^n :: real)" (is "inj ?f")
proof (rule injI)
  have x: "\<And>a b :: real. (0 < a \<and> b < 0) \<or> (a < 0 \<and> 0 < b) \<Longrightarrow> a \<noteq> b" by auto
  fix x y assume "?f x = ?f y" with power_eq_iff_eq_base[of n "\<bar>x\<bar>" "\<bar>y\<bar>"] `0<n` show "x = y"
    by (cases rule: linorder_cases[of 0 x, case_product linorder_cases[of 0 y]])
       (simp_all add: x)
qed

lemma sgn_power_injE: "sgn a * \<bar>a\<bar> ^ n = x \<Longrightarrow> x = sgn b * \<bar>b\<bar> ^ n \<Longrightarrow> 0 < n \<Longrightarrow> a = (b::real)"
  using inj_sgn_power[THEN injD, of n a b] by simp

definition root :: "nat \<Rightarrow> real \<Rightarrow> real" where
  "root n x = (if n = 0 then 0 else the_inv (\<lambda>y. sgn y * \<bar>y\<bar>^n) x)"

lemma root_0 [simp]: "root 0 x = 0"
  by (simp add: root_def)

lemma root_sgn_power: "0 < n \<Longrightarrow> root n (sgn y * \<bar>y\<bar>^n) = y"
  using the_inv_f_f[OF inj_sgn_power] by (simp add: root_def)

lemma sgn_power_root:
  assumes "0 < n" shows "sgn (root n x) * \<bar>(root n x)\<bar>^n = x" (is "?f (root n x) = x")
proof cases
  assume "x \<noteq> 0"
  with realpow_pos_nth[OF `0 < n`, of "\<bar>x\<bar>"] obtain r where "0 < r" "r ^ n = \<bar>x\<bar>" by auto
  with `x \<noteq> 0` have S: "x \<in> range ?f"
    by (intro image_eqI[of _ _ "sgn x * r"])
       (auto simp: abs_mult sgn_mult power_mult_distrib abs_sgn_eq mult_sgn_abs)
  from `0 < n` f_the_inv_into_f[OF inj_sgn_power[OF `0 < n`] this]  show ?thesis
    by (simp add: root_def)
qed (insert `0 < n` root_sgn_power[of n 0], simp)

lemma split_root: "P (root n x) \<longleftrightarrow> (n = 0 \<longrightarrow> P 0) \<and> (0 < n \<longrightarrow> (\<forall>y. sgn y * \<bar>y\<bar>^n = x \<longrightarrow> P y))"
  apply (cases "n = 0")
  apply simp_all
  apply (metis root_sgn_power sgn_power_root)
  done

lemma real_root_zero [simp]: "root n 0 = 0"
  by (simp split: split_root add: sgn_zero_iff)

lemma real_root_minus: "root n (- x) = - root n x"
  by (clarsimp split: split_root elim!: sgn_power_injE simp: sgn_minus)

lemma real_root_less_mono: "\<lbrakk>0 < n; x < y\<rbrakk> \<Longrightarrow> root n x < root n y"
proof (clarsimp split: split_root)
  have x: "\<And>a b :: real. (0 < b \<and> a < 0) \<Longrightarrow> \<not> a > b" by auto
  fix a b :: real assume "0 < n" "sgn a * \<bar>a\<bar> ^ n < sgn b * \<bar>b\<bar> ^ n" then show "a < b"
    using power_less_imp_less_base[of a n b]  power_less_imp_less_base[of "-b" n "-a"]
    by (simp add: sgn_real_def power_less_zero_eq x[of "a ^ n" "- ((- b) ^ n)"] split: split_if_asm)
qed

lemma real_root_gt_zero: "\<lbrakk>0 < n; 0 < x\<rbrakk> \<Longrightarrow> 0 < root n x"
  using real_root_less_mono[of n 0 x] by simp

lemma real_root_ge_zero: "0 \<le> x \<Longrightarrow> 0 \<le> root n x"
  using real_root_gt_zero[of n x] by (cases "n = 0") (auto simp add: le_less)

lemma real_root_pow_pos: (* TODO: rename *)
  "\<lbrakk>0 < n; 0 < x\<rbrakk> \<Longrightarrow> root n x ^ n = x"
  using sgn_power_root[of n x] real_root_gt_zero[of n x] by simp

lemma real_root_pow_pos2 [simp]: (* TODO: rename *)
  "\<lbrakk>0 < n; 0 \<le> x\<rbrakk> \<Longrightarrow> root n x ^ n = x"
by (auto simp add: order_le_less real_root_pow_pos)

lemma sgn_root: "0 < n \<Longrightarrow> sgn (root n x) = sgn x"
  by (auto split: split_root simp: sgn_real_def power_less_zero_eq)

lemma odd_real_root_pow: "odd n \<Longrightarrow> root n x ^ n = x"
  using sgn_power_root[of n x] by (simp add: odd_pos sgn_real_def split: split_if_asm)

lemma real_root_power_cancel: "\<lbrakk>0 < n; 0 \<le> x\<rbrakk> \<Longrightarrow> root n (x ^ n) = x"
  using root_sgn_power[of n x] by (auto simp add: le_less power_0_left)

lemma odd_real_root_power_cancel: "odd n \<Longrightarrow> root n (x ^ n) = x"
  using root_sgn_power[of n x] by (simp add: odd_pos sgn_real_def power_0_left split: split_if_asm)

lemma real_root_pos_unique: "\<lbrakk>0 < n; 0 \<le> y; y ^ n = x\<rbrakk> \<Longrightarrow> root n x = y"
  using root_sgn_power[of n y] by (auto simp add: le_less power_0_left)

lemma odd_real_root_unique:
  "\<lbrakk>odd n; y ^ n = x\<rbrakk> \<Longrightarrow> root n x = y"
by (erule subst, rule odd_real_root_power_cancel)

lemma real_root_one [simp]: "0 < n \<Longrightarrow> root n 1 = 1"
by (simp add: real_root_pos_unique)

text {* Root function is strictly monotonic, hence injective *}

lemma real_root_le_mono: "\<lbrakk>0 < n; x \<le> y\<rbrakk> \<Longrightarrow> root n x \<le> root n y"
  by (auto simp add: order_le_less real_root_less_mono)

lemma real_root_less_iff [simp]:
  "0 < n \<Longrightarrow> (root n x < root n y) = (x < y)"
apply (cases "x < y")
apply (simp add: real_root_less_mono)
apply (simp add: linorder_not_less real_root_le_mono)
done

lemma real_root_le_iff [simp]:
  "0 < n \<Longrightarrow> (root n x \<le> root n y) = (x \<le> y)"
apply (cases "x \<le> y")
apply (simp add: real_root_le_mono)
apply (simp add: linorder_not_le real_root_less_mono)
done

lemma real_root_eq_iff [simp]:
  "0 < n \<Longrightarrow> (root n x = root n y) = (x = y)"
by (simp add: order_eq_iff)

lemmas real_root_gt_0_iff [simp] = real_root_less_iff [where x=0, simplified]
lemmas real_root_lt_0_iff [simp] = real_root_less_iff [where y=0, simplified]
lemmas real_root_ge_0_iff [simp] = real_root_le_iff [where x=0, simplified]
lemmas real_root_le_0_iff [simp] = real_root_le_iff [where y=0, simplified]
lemmas real_root_eq_0_iff [simp] = real_root_eq_iff [where y=0, simplified]

lemma real_root_gt_1_iff [simp]: "0 < n \<Longrightarrow> (1 < root n y) = (1 < y)"
by (insert real_root_less_iff [where x=1], simp)

lemma real_root_lt_1_iff [simp]: "0 < n \<Longrightarrow> (root n x < 1) = (x < 1)"
by (insert real_root_less_iff [where y=1], simp)

lemma real_root_ge_1_iff [simp]: "0 < n \<Longrightarrow> (1 \<le> root n y) = (1 \<le> y)"
by (insert real_root_le_iff [where x=1], simp)

lemma real_root_le_1_iff [simp]: "0 < n \<Longrightarrow> (root n x \<le> 1) = (x \<le> 1)"
by (insert real_root_le_iff [where y=1], simp)

lemma real_root_eq_1_iff [simp]: "0 < n \<Longrightarrow> (root n x = 1) = (x = 1)"
by (insert real_root_eq_iff [where y=1], simp)

text {* Roots of multiplication and division *}

lemma real_root_mult: "root n (x * y) = root n x * root n y"
  by (auto split: split_root elim!: sgn_power_injE simp: sgn_mult abs_mult power_mult_distrib)

lemma real_root_inverse: "root n (inverse x) = inverse (root n x)"
  by (auto split: split_root elim!: sgn_power_injE simp: inverse_sgn power_inverse)

lemma real_root_divide: "root n (x / y) = root n x / root n y"
  by (simp add: divide_inverse real_root_mult real_root_inverse)

lemma real_root_abs: "0 < n \<Longrightarrow> root n \<bar>x\<bar> = \<bar>root n x\<bar>"
  by (simp add: abs_if real_root_minus)

lemma real_root_power: "0 < n \<Longrightarrow> root n (x ^ k) = root n x ^ k"
  by (induct k) (simp_all add: real_root_mult)

text {* Roots of roots *}

lemma real_root_Suc_0 [simp]: "root (Suc 0) x = x"
by (simp add: odd_real_root_unique)

lemma real_root_mult_exp: "root (m * n) x = root m (root n x)"
  by (auto split: split_root elim!: sgn_power_injE
           simp: sgn_zero_iff sgn_mult power_mult[symmetric] abs_mult power_mult_distrib abs_sgn_eq)

lemma real_root_commute: "root m (root n x) = root n (root m x)"
  by (simp add: real_root_mult_exp [symmetric] mult.commute)

text {* Monotonicity in first argument *}

lemma real_root_strict_decreasing:
  "\<lbrakk>0 < n; n < N; 1 < x\<rbrakk> \<Longrightarrow> root N x < root n x"
apply (subgoal_tac "root n (root N x) ^ n < root N (root n x) ^ N", simp)
apply (simp add: real_root_commute power_strict_increasing
            del: real_root_pow_pos2)
done

lemma real_root_strict_increasing:
  "\<lbrakk>0 < n; n < N; 0 < x; x < 1\<rbrakk> \<Longrightarrow> root n x < root N x"
apply (subgoal_tac "root N (root n x) ^ N < root n (root N x) ^ n", simp)
apply (simp add: real_root_commute power_strict_decreasing
            del: real_root_pow_pos2)
done

lemma real_root_decreasing:
  "\<lbrakk>0 < n; n < N; 1 \<le> x\<rbrakk> \<Longrightarrow> root N x \<le> root n x"
by (auto simp add: order_le_less real_root_strict_decreasing)

lemma real_root_increasing:
  "\<lbrakk>0 < n; n < N; 0 \<le> x; x \<le> 1\<rbrakk> \<Longrightarrow> root n x \<le> root N x"
by (auto simp add: order_le_less real_root_strict_increasing)

text {* Continuity and derivatives *}

lemma isCont_real_root: "isCont (root n) x"
proof cases
  assume n: "0 < n"
  let ?f = "\<lambda>y::real. sgn y * \<bar>y\<bar>^n"
  have "continuous_on ({0..} \<union> {.. 0}) (\<lambda>x. if 0 < x then x ^ n else - ((-x) ^ n) :: real)"
    using n by (intro continuous_on_If continuous_intros) auto
  then have "continuous_on UNIV ?f"
    by (rule continuous_on_cong[THEN iffD1, rotated 2]) (auto simp: not_less real_sgn_neg le_less n)
  then have [simp]: "\<And>x. isCont ?f x"
    by (simp add: continuous_on_eq_continuous_at)

  have "isCont (root n) (?f (root n x))"
    by (rule isCont_inverse_function [where f="?f" and d=1]) (auto simp: root_sgn_power n)
  then show ?thesis
    by (simp add: sgn_power_root n)
qed (simp add: root_def[abs_def])

lemma tendsto_real_root[tendsto_intros]:
  "(f ---> x) F \<Longrightarrow> ((\<lambda>x. root n (f x)) ---> root n x) F"
  using isCont_tendsto_compose[OF isCont_real_root, of f x F] .

lemma continuous_real_root[continuous_intros]:
  "continuous F f \<Longrightarrow> continuous F (\<lambda>x. root n (f x))"
  unfolding continuous_def by (rule tendsto_real_root)

lemma continuous_on_real_root[continuous_intros]:
  "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. root n (f x))"
  unfolding continuous_on_def by (auto intro: tendsto_real_root)

lemma DERIV_real_root:
  assumes n: "0 < n"
  assumes x: "0 < x"
  shows "DERIV (root n) x :> inverse (real n * root n x ^ (n - Suc 0))"
proof (rule DERIV_inverse_function)
  show "0 < x" using x .
  show "x < x + 1" by simp
  show "\<forall>y. 0 < y \<and> y < x + 1 \<longrightarrow> root n y ^ n = y"
    using n by simp
  show "DERIV (\<lambda>x. x ^ n) (root n x) :> real n * root n x ^ (n - Suc 0)"
    by (rule DERIV_pow)
  show "real n * root n x ^ (n - Suc 0) \<noteq> 0"
    using n x by simp
qed (rule isCont_real_root)

lemma DERIV_odd_real_root:
  assumes n: "odd n"
  assumes x: "x \<noteq> 0"
  shows "DERIV (root n) x :> inverse (real n * root n x ^ (n - Suc 0))"
proof (rule DERIV_inverse_function)
  show "x - 1 < x" by simp
  show "x < x + 1" by simp
  show "\<forall>y. x - 1 < y \<and> y < x + 1 \<longrightarrow> root n y ^ n = y"
    using n by (simp add: odd_real_root_pow)
  show "DERIV (\<lambda>x. x ^ n) (root n x) :> real n * root n x ^ (n - Suc 0)"
    by (rule DERIV_pow)
  show "real n * root n x ^ (n - Suc 0) \<noteq> 0"
    using odd_pos [OF n] x by simp
qed (rule isCont_real_root)

lemma DERIV_even_real_root:
  assumes n: "0 < n" and "even n"
  assumes x: "x < 0"
  shows "DERIV (root n) x :> inverse (- real n * root n x ^ (n - Suc 0))"
proof (rule DERIV_inverse_function)
  show "x - 1 < x" by simp
  show "x < 0" using x .
next
  show "\<forall>y. x - 1 < y \<and> y < 0 \<longrightarrow> - (root n y ^ n) = y"
  proof (rule allI, rule impI, erule conjE)
    fix y assume "x - 1 < y" and "y < 0"
    hence "root n (-y) ^ n = -y" using `0 < n` by simp
    with real_root_minus and `even n`
    show "- (root n y ^ n) = y" by simp
  qed
next
  show "DERIV (\<lambda>x. - (x ^ n)) (root n x) :> - real n * root n x ^ (n - Suc 0)"
    by  (auto intro!: derivative_eq_intros simp: real_of_nat_def)
  show "- real n * root n x ^ (n - Suc 0) \<noteq> 0"
    using n x by simp
qed (rule isCont_real_root)

lemma DERIV_real_root_generic:
  assumes "0 < n" and "x \<noteq> 0"
    and "\<lbrakk> even n ; 0 < x \<rbrakk> \<Longrightarrow> D = inverse (real n * root n x ^ (n - Suc 0))"
    and "\<lbrakk> even n ; x < 0 \<rbrakk> \<Longrightarrow> D = - inverse (real n * root n x ^ (n - Suc 0))"
    and "odd n \<Longrightarrow> D = inverse (real n * root n x ^ (n - Suc 0))"
  shows "DERIV (root n) x :> D"
using assms by (cases "even n", cases "0 < x",
  auto intro: DERIV_real_root[THEN DERIV_cong]
              DERIV_odd_real_root[THEN DERIV_cong]
              DERIV_even_real_root[THEN DERIV_cong])

subsection {* Square Root *}

definition sqrt :: "real \<Rightarrow> real" where
  "sqrt = root 2"

lemma pos2: "0 < (2::nat)" by simp

lemma real_sqrt_unique: "\<lbrakk>y\<^sup>2 = x; 0 \<le> y\<rbrakk> \<Longrightarrow> sqrt x = y"
unfolding sqrt_def by (rule real_root_pos_unique [OF pos2])

lemma real_sqrt_abs [simp]: "sqrt (x\<^sup>2) = \<bar>x\<bar>"
apply (rule real_sqrt_unique)
apply (rule power2_abs)
apply (rule abs_ge_zero)
done

lemma real_sqrt_pow2 [simp]: "0 \<le> x \<Longrightarrow> (sqrt x)\<^sup>2 = x"
unfolding sqrt_def by (rule real_root_pow_pos2 [OF pos2])

lemma real_sqrt_pow2_iff [simp]: "((sqrt x)\<^sup>2 = x) = (0 \<le> x)"
apply (rule iffI)
apply (erule subst)
apply (rule zero_le_power2)
apply (erule real_sqrt_pow2)
done

lemma real_sqrt_zero [simp]: "sqrt 0 = 0"
unfolding sqrt_def by (rule real_root_zero)

lemma real_sqrt_one [simp]: "sqrt 1 = 1"
unfolding sqrt_def by (rule real_root_one [OF pos2])

lemma real_sqrt_four [simp]: "sqrt 4 = 2"
  using real_sqrt_abs[of 2] by simp

lemma real_sqrt_minus: "sqrt (- x) = - sqrt x"
unfolding sqrt_def by (rule real_root_minus)

lemma real_sqrt_mult: "sqrt (x * y) = sqrt x * sqrt y"
unfolding sqrt_def by (rule real_root_mult)

lemma real_sqrt_mult_self[simp]: "sqrt a * sqrt a = \<bar>a\<bar>"
  using real_sqrt_abs[of a] unfolding power2_eq_square real_sqrt_mult .

lemma real_sqrt_inverse: "sqrt (inverse x) = inverse (sqrt x)"
unfolding sqrt_def by (rule real_root_inverse)

lemma real_sqrt_divide: "sqrt (x / y) = sqrt x / sqrt y"
unfolding sqrt_def by (rule real_root_divide)

lemma real_sqrt_power: "sqrt (x ^ k) = sqrt x ^ k"
unfolding sqrt_def by (rule real_root_power [OF pos2])

lemma real_sqrt_gt_zero: "0 < x \<Longrightarrow> 0 < sqrt x"
unfolding sqrt_def by (rule real_root_gt_zero [OF pos2])

lemma real_sqrt_ge_zero: "0 \<le> x \<Longrightarrow> 0 \<le> sqrt x"
unfolding sqrt_def by (rule real_root_ge_zero)

lemma real_sqrt_less_mono: "x < y \<Longrightarrow> sqrt x < sqrt y"
unfolding sqrt_def by (rule real_root_less_mono [OF pos2])

lemma real_sqrt_le_mono: "x \<le> y \<Longrightarrow> sqrt x \<le> sqrt y"
unfolding sqrt_def by (rule real_root_le_mono [OF pos2])

lemma real_sqrt_less_iff [simp]: "(sqrt x < sqrt y) = (x < y)"
unfolding sqrt_def by (rule real_root_less_iff [OF pos2])

lemma real_sqrt_le_iff [simp]: "(sqrt x \<le> sqrt y) = (x \<le> y)"
unfolding sqrt_def by (rule real_root_le_iff [OF pos2])

lemma real_sqrt_eq_iff [simp]: "(sqrt x = sqrt y) = (x = y)"
unfolding sqrt_def by (rule real_root_eq_iff [OF pos2])

lemma real_le_lsqrt: "0 \<le> x \<Longrightarrow> 0 \<le> y \<Longrightarrow> x \<le> y\<^sup>2 \<Longrightarrow> sqrt x \<le> y"
  using real_sqrt_le_iff[of x "y\<^sup>2"] by simp

lemma real_le_rsqrt: "x\<^sup>2 \<le> y \<Longrightarrow> x \<le> sqrt y"
  using real_sqrt_le_mono[of "x\<^sup>2" y] by simp

lemma real_less_rsqrt: "x\<^sup>2 < y \<Longrightarrow> x < sqrt y"
  using real_sqrt_less_mono[of "x\<^sup>2" y] by simp

lemma sqrt_even_pow2:
  assumes n: "even n"
  shows "sqrt (2 ^ n) = 2 ^ (n div 2)"
proof -
  from n obtain m where m: "n = 2 * m" ..
  from m have "sqrt (2 ^ n) = sqrt ((2 ^ m)\<^sup>2)"
    by (simp only: power_mult[symmetric] mult.commute)
  then show ?thesis
    using m by simp
qed

lemmas real_sqrt_gt_0_iff [simp] = real_sqrt_less_iff [where x=0, unfolded real_sqrt_zero]
lemmas real_sqrt_lt_0_iff [simp] = real_sqrt_less_iff [where y=0, unfolded real_sqrt_zero]
lemmas real_sqrt_ge_0_iff [simp] = real_sqrt_le_iff [where x=0, unfolded real_sqrt_zero]
lemmas real_sqrt_le_0_iff [simp] = real_sqrt_le_iff [where y=0, unfolded real_sqrt_zero]
lemmas real_sqrt_eq_0_iff [simp] = real_sqrt_eq_iff [where y=0, unfolded real_sqrt_zero]

lemmas real_sqrt_gt_1_iff [simp] = real_sqrt_less_iff [where x=1, unfolded real_sqrt_one]
lemmas real_sqrt_lt_1_iff [simp] = real_sqrt_less_iff [where y=1, unfolded real_sqrt_one]
lemmas real_sqrt_ge_1_iff [simp] = real_sqrt_le_iff [where x=1, unfolded real_sqrt_one]
lemmas real_sqrt_le_1_iff [simp] = real_sqrt_le_iff [where y=1, unfolded real_sqrt_one]
lemmas real_sqrt_eq_1_iff [simp] = real_sqrt_eq_iff [where y=1, unfolded real_sqrt_one]

lemma isCont_real_sqrt: "isCont sqrt x"
unfolding sqrt_def by (rule isCont_real_root)

lemma tendsto_real_sqrt[tendsto_intros]:
  "(f ---> x) F \<Longrightarrow> ((\<lambda>x. sqrt (f x)) ---> sqrt x) F"
  unfolding sqrt_def by (rule tendsto_real_root)

lemma continuous_real_sqrt[continuous_intros]:
  "continuous F f \<Longrightarrow> continuous F (\<lambda>x. sqrt (f x))"
  unfolding sqrt_def by (rule continuous_real_root)

lemma continuous_on_real_sqrt[continuous_intros]:
  "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. sqrt (f x))"
  unfolding sqrt_def by (rule continuous_on_real_root)

lemma DERIV_real_sqrt_generic:
  assumes "x \<noteq> 0"
  assumes "x > 0 \<Longrightarrow> D = inverse (sqrt x) / 2"
  assumes "x < 0 \<Longrightarrow> D = - inverse (sqrt x) / 2"
  shows "DERIV sqrt x :> D"
  using assms unfolding sqrt_def
  by (auto intro!: DERIV_real_root_generic)

lemma DERIV_real_sqrt:
  "0 < x \<Longrightarrow> DERIV sqrt x :> inverse (sqrt x) / 2"
  using DERIV_real_sqrt_generic by simp

declare
  DERIV_real_sqrt_generic[THEN DERIV_chain2, derivative_intros]
  DERIV_real_root_generic[THEN DERIV_chain2, derivative_intros]

lemma not_real_square_gt_zero [simp]: "(~ (0::real) < x*x) = (x = 0)"
apply auto
apply (cut_tac x = x and y = 0 in linorder_less_linear)
apply (simp add: zero_less_mult_iff)
done

lemma real_sqrt_abs2 [simp]: "sqrt(x*x) = \<bar>x\<bar>"
apply (subst power2_eq_square [symmetric])
apply (rule real_sqrt_abs)
done

lemma real_inv_sqrt_pow2: "0 < x ==> (inverse (sqrt x))\<^sup>2 = inverse x"
by (simp add: power_inverse [symmetric])

lemma real_sqrt_eq_zero_cancel: "[| 0 \<le> x; sqrt(x) = 0|] ==> x = 0"
by simp

lemma real_sqrt_ge_one: "1 \<le> x ==> 1 \<le> sqrt x"
by simp

lemma sqrt_divide_self_eq:
  assumes nneg: "0 \<le> x"
  shows "sqrt x / x = inverse (sqrt x)"
proof cases
  assume "x=0" thus ?thesis by simp
next
  assume nz: "x\<noteq>0"
  hence pos: "0<x" using nneg by arith
  show ?thesis
  proof (rule right_inverse_eq [THEN iffD1, THEN sym])
    show "sqrt x / x \<noteq> 0" by (simp add: divide_inverse nneg nz)
    show "inverse (sqrt x) / (sqrt x / x) = 1"
      by (simp add: divide_inverse mult.assoc [symmetric]
                  power2_eq_square [symmetric] real_inv_sqrt_pow2 pos nz)
  qed
qed

lemma real_div_sqrt: "0 \<le> x \<Longrightarrow> x / sqrt x = sqrt x"
  apply (cases "x = 0")
  apply simp_all
  using sqrt_divide_self_eq[of x]
  apply (simp add: inverse_eq_divide field_simps)
  done

lemma real_divide_square_eq [simp]: "(((r::real) * a) / (r * r)) = a / r"
apply (simp add: divide_inverse)
apply (case_tac "r=0")
apply (auto simp add: ac_simps)
done

lemma lemma_real_divide_sqrt_less: "0 < u ==> u / sqrt 2 < u"
by (simp add: divide_less_eq)

lemma four_x_squared:
  fixes x::real
  shows "4 * x\<^sup>2 = (2 * x)\<^sup>2"
by (simp add: power2_eq_square)

lemma sqrt_at_top: "LIM x at_top. sqrt x :: real :> at_top"
  by (rule filterlim_at_top_at_top[where Q="\<lambda>x. True" and P="\<lambda>x. 0 < x" and g="power2"])
     (auto intro: eventually_gt_at_top)

subsection {* Square Root of Sum of Squares *}

lemma sum_squares_bound:
  fixes x:: "'a::linordered_field"
  shows "2*x*y \<le> x^2 + y^2"
proof -
  have "(x-y)^2 = x*x - 2*x*y + y*y"
    by algebra
  then have "0 \<le> x^2 - 2*x*y + y^2"
    by (metis sum_power2_ge_zero zero_le_double_add_iff_zero_le_single_add power2_eq_square)
  then show ?thesis
    by arith
qed

lemma arith_geo_mean:
  fixes u:: "'a::linordered_field" assumes "u\<^sup>2 = x*y" "x\<ge>0" "y\<ge>0" shows "u \<le> (x + y)/2"
    apply (rule power2_le_imp_le)
    using sum_squares_bound assms
    apply (auto simp: zero_le_mult_iff)
    by (auto simp: algebra_simps power2_eq_square)

lemma arith_geo_mean_sqrt:
  fixes x::real assumes "x\<ge>0" "y\<ge>0" shows "sqrt(x*y) \<le> (x + y)/2"
  apply (rule arith_geo_mean)
  using assms
  apply (auto simp: zero_le_mult_iff)
  done

lemma real_sqrt_sum_squares_mult_ge_zero [simp]:
     "0 \<le> sqrt ((x\<^sup>2 + y\<^sup>2)*(xa\<^sup>2 + ya\<^sup>2))"
  by (metis real_sqrt_ge_0_iff split_mult_pos_le sum_power2_ge_zero)

lemma real_sqrt_sum_squares_mult_squared_eq [simp]:
     "(sqrt ((x\<^sup>2 + y\<^sup>2) * (xa\<^sup>2 + ya\<^sup>2)))\<^sup>2 = (x\<^sup>2 + y\<^sup>2) * (xa\<^sup>2 + ya\<^sup>2)"
  by (simp add: zero_le_mult_iff)

lemma real_sqrt_sum_squares_eq_cancel: "sqrt (x\<^sup>2 + y\<^sup>2) = x \<Longrightarrow> y = 0"
by (drule_tac f = "%x. x\<^sup>2" in arg_cong, simp)

lemma real_sqrt_sum_squares_eq_cancel2: "sqrt (x\<^sup>2 + y\<^sup>2) = y \<Longrightarrow> x = 0"
by (drule_tac f = "%x. x\<^sup>2" in arg_cong, simp)

lemma real_sqrt_sum_squares_ge1 [simp]: "x \<le> sqrt (x\<^sup>2 + y\<^sup>2)"
by (rule power2_le_imp_le, simp_all)

lemma real_sqrt_sum_squares_ge2 [simp]: "y \<le> sqrt (x\<^sup>2 + y\<^sup>2)"
by (rule power2_le_imp_le, simp_all)

lemma real_sqrt_ge_abs1 [simp]: "\<bar>x\<bar> \<le> sqrt (x\<^sup>2 + y\<^sup>2)"
by (rule power2_le_imp_le, simp_all)

lemma real_sqrt_ge_abs2 [simp]: "\<bar>y\<bar> \<le> sqrt (x\<^sup>2 + y\<^sup>2)"
by (rule power2_le_imp_le, simp_all)

lemma le_real_sqrt_sumsq [simp]: "x \<le> sqrt (x * x + y * y)"
by (simp add: power2_eq_square [symmetric])

lemma real_sqrt_sum_squares_triangle_ineq:
  "sqrt ((a + c)\<^sup>2 + (b + d)\<^sup>2) \<le> sqrt (a\<^sup>2 + b\<^sup>2) + sqrt (c\<^sup>2 + d\<^sup>2)"
apply (rule power2_le_imp_le, simp)
apply (simp add: power2_sum)
apply (simp only: mult.assoc distrib_left [symmetric])
apply (rule mult_left_mono)
apply (rule power2_le_imp_le)
apply (simp add: power2_sum power_mult_distrib)
apply (simp add: ring_distribs)
apply (subgoal_tac "0 \<le> b\<^sup>2 * c\<^sup>2 + a\<^sup>2 * d\<^sup>2 - 2 * (a * c) * (b * d)", simp)
apply (rule_tac b="(a * d - b * c)\<^sup>2" in ord_le_eq_trans)
apply (rule zero_le_power2)
apply (simp add: power2_diff power_mult_distrib)
apply (simp)
apply simp
apply (simp add: add_increasing)
done

lemma real_sqrt_sum_squares_less:
  "\<lbrakk>\<bar>x\<bar> < u / sqrt 2; \<bar>y\<bar> < u / sqrt 2\<rbrakk> \<Longrightarrow> sqrt (x\<^sup>2 + y\<^sup>2) < u"
apply (rule power2_less_imp_less, simp)
apply (drule power_strict_mono [OF _ abs_ge_zero pos2])
apply (drule power_strict_mono [OF _ abs_ge_zero pos2])
apply (simp add: power_divide)
apply (drule order_le_less_trans [OF abs_ge_zero])
apply (simp add: zero_less_divide_iff)
done

text{*Needed for the infinitely close relation over the nonstandard
    complex numbers*}
lemma lemma_sqrt_hcomplex_capprox:
     "[| 0 < u; x < u/2; y < u/2; 0 \<le> x; 0 \<le> y |] ==> sqrt (x\<^sup>2 + y\<^sup>2) < u"
apply (rule_tac y = "u/sqrt 2" in order_le_less_trans)
apply (erule_tac [2] lemma_real_divide_sqrt_less)
apply (rule power2_le_imp_le)
apply (auto simp add: zero_le_divide_iff power_divide)
apply (rule_tac t = "u\<^sup>2" in real_sum_of_halves [THEN subst])
apply (rule add_mono)
apply (auto simp add: four_x_squared intro: power_mono)
done

text "Legacy theorem names:"
lemmas real_root_pos2 = real_root_power_cancel
lemmas real_root_pos_pos = real_root_gt_zero [THEN order_less_imp_le]
lemmas real_root_pos_pos_le = real_root_ge_zero
lemmas real_sqrt_mult_distrib = real_sqrt_mult
lemmas real_sqrt_mult_distrib2 = real_sqrt_mult
lemmas real_sqrt_eq_zero_cancel_iff = real_sqrt_eq_0_iff

(* needed for CauchysMeanTheorem.het_base from AFP *)
lemma real_root_pos: "0 < x \<Longrightarrow> root (Suc n) (x ^ (Suc n)) = x"
by (rule real_root_power_cancel [OF zero_less_Suc order_less_imp_le])

end