\chapter{Hoare Logic}
In this chapter we introduce \href{http://en.wikipedia.org/wiki/Hoare_logic}{\emph{Hoare logic}}.
This is a formal system that is used to prove the correctness of imperative computer programs.
Hoare logic has been introduced 1969 by
\href{http://en.wikipedia.org/wiki/C._A._R._Hoare}{Sir Charles Antony Richard Hoare},
who is the inventor of the \href{http://en.wikipedia.org/wiki/Quicksort}{quicksort} algorithm.

\section{Preconditions and Postconditions}
Hoare logic is based on preconditions and postconditions.  If \texttt{P}
 is a program fragment and if $F$ and $G$ are logical formul\ae, then we call
$F$ a precondition and $G$ a postcondition for the program fragment \texttt{P}
if the following holds:  If \texttt{P} is executed in a state $s$ such that the formula $F$ holds in
$s$, then the execution of \texttt{P} will change the state $s$ into a new state $s'$ such that
$G$ holds in $s'$.  This is written as
\\[0.2cm]
\hspace*{1.3cm}
$ \hoare{F}{P}{G} $.
\\[0.2cm]
We will read this notation as ``\emph{executing $P$ changes $F$ into $G$}''.
The formula
\\[0.2cm]
\hspace*{1.3cm}
$ \hoare{F}{P}{G} $
\\[0.2cm]
is called a \emph{Hoare triple}.
\vspace*{0.3cm}

\examplesEng
\begin{enumerate}
\item The assignment ``\texttt{x := 1;}'' satisfies the specification
      \\[0.2cm]
      \hspace*{1.3cm}
      $ \hoare{\mathtt{true}}{x := 1;}{x = 1}. $
      \\[0.2cm]
      Here, the precondition is the trivial condition ``\texttt{true}'', since
      the postcondition ``$x = 1$'' will always be satisfied after this assignment.
\item The assignment  ``\texttt{x = x + 1;}'' satisfies the specification
      \\[0.2cm]
      \hspace*{1.3cm}
      $ \hoare{x=1}{x := x + 1;}{x=2}. $
      \\[0.2cm]
      If the precondition is ``$x = 1$'', then it is obvious that the postcondition has to be
      ``$x = 2$''.
\item Let us consider the assignment ``\texttt{x = x + 1;}'' again.  However, this time
      the precondition is given as ``$\textsl{prime}(x)$'', which is only true if $x$ is a
      prime number.  This time, the Hoare triple is given as
      \\[0.2cm]
      \hspace*{1.3cm}
      $ \hoare{\textsl{prime}(x)}{x := x + 1;}{\textsl{prime}(x-1)}$.
      \\[0.2cm]
      This might look strange at first.  Many students think that this Hoare triple should rather
      be written as
      \\[0.2cm]
      \hspace*{1.3cm}
      $ \hoare{\textsl{prime}(x)}{x := x + 1;}{\textsl{prime}(x+1)} $.
      \\[0.2cm]
      However, this can easily be refuted by taking $x$ to have the value $2$.  Then, the
      precondition $\textsl{prime}(x)$ is satisfied since $2$ is a prime number.  After the
      assignment, $x$ has the value $3$ and
      \\[0.2cm]
      \hspace*{1.3cm}
      $x - 1 = 3 - 1 = 2$
      \\[0.2cm]
      still is a prime number.  However, we also have
      \\[0.2cm]
      \hspace*{1.3cm}
      $x + 1 = 3 + 1 = 4$
      \\[0.2cm]
      and as $4 = 2 \cdot 2$ we see that $x + 1$ is not a prime number!
\end{enumerate}
Let us proceed to show how the different parts of a program can be specified using Hoare triples.
We start with the analysis of assignments.

\subsection{Assignments}
Let us generalize the previous example.  Let us therefore assume that we have an assignment of the
form
\\[0.2cm]
\hspace*{1.3cm}
$ \texttt{x := h(x);} $
\\[0.2cm]
and we want to investigate how the postcondition $G$ of this assignment is related to the
precondition $F$.  To simplify matters, let us assume that the function
$h$ is invertible, i.~e.~we assume that there is a function $h^{-1}$ such that we have
\\[0.2cm]
\hspace*{1.3cm}
$ h^{-1}\bigl(h(x)\bigr) = x \quad \mathtt{and} \quad h\bigl(h^{-1}(x)\bigr) = x $
\\[0.2cm]
for all $x$.  Then, the function $h^{-1}$ is the inverse of the function $h$.
In order to understand the problem of computing the postcondition for the assignment statement given
above, let us first consider an example.  The assignment
\\[0.2cm]
\hspace*{1.3cm}
$ \texttt{x := x + 1;} $
\\[0.2cm]
can be written as
\\[0.2cm]
\hspace*{1.3cm}
$ \texttt{x := h(x);} $
\\[0.2cm]
where the function $h$ is given as
\\[0.2cm]
\hspace*{1.3cm}
$ h(x) = x + 1 $
\\[0.2cm]
and the inverse function $h^{-1}$ is
\\[0.2cm]
\hspace*{1.3cm}
$h^{-1}(x) = x - 1$.
\\[0.2cm]
Now we are able to compute the postcondition of the assignment ``\texttt{x := h(x);}'' from the
precondition.  We have
\\[0.2cm]
\hspace*{1.3cm}
$\hoare{F}{x := h(x);}{F\sigma}$ \quad where \quad
$\sigma = \bigl[x \mapsto h^{-1}(x)\bigr]$.
\\[0.2cm]
Here, $F\sigma$ denotes the application of the substitution $\sigma$ to the formula $F$.  The
expression  $F\sigma$ is computed from the expression $F$ by replacing every occurrence of the variable
$x$ by the term $h^{-1}(x)$.  Therefore, the substitution $\sigma$ undoes the effect of the
assignment and restores the variables in $F$ to the state before the assignment.

In order to understand why this is the correct way to compute the
postcondition, we consider the assignment
``\texttt{x := x + 1}'' again and choose the formula $x = 7$ as precondition.
Since $h^{-1}(x) = x - 1$, the substitution $\sigma$ is given as
$\sigma = [ x \mapsto x - 1 ]$.  Therefore, $F\sigma$ has the form
\\[0.2cm]
\hspace*{1.3cm}
$ (x = 7)[x \mapsto x - 1] \;\equiv\; (x - 1 = 7). $
\\[0.2cm]
I have used the symbol ``$\equiv$'' here in order to express that these formul\ae\ are
syntactically identical.
Therefore, we have
\\[0.2cm]
\hspace*{1.3cm}
$ \hoare{x = 7}{x := x + 1;}{x - 1 = 7}. $
\\[0.2cm]
Since the formula $x - 1 = 7$ is equivalent to the formula $x = 8$ the Hoare triple above can be
rewritten as
\\[0.2cm]
\hspace*{1.3cm}
$ \hoare{x = 7}{x := x + 1;}{x = 8} $
\\[0.2cm]
and this is obviously correct:  If the value of $x$ is $7$ before the assignment
\\[0.2cm]
\hspace*{1.3cm}
``\texttt{x := x + 1;}''
\\[0.2cm]
is executed, then after the assignment is executed, $x$ will have the value $8$.

Let us try to understand why
\\[0.2cm]
\hspace*{1.3cm}
$\hoare{F}{x := h(x);}{F\sigma}$ \quad where \quad
$\sigma = \bigl[x \mapsto h^{-1}(x)\bigr] $
\\[0.2cm]
is, indeed, correct:   Before the assignment ``x \texttt{:=} h(x);'' is executed,
the variable $x$ has some fixed value $x_0$.  The precondition $F$ is valid for $x_0$.  Therefore,
the formula $F[x \mapsto x_0]$ is valid before the assignment is executed.  However,
the variable $x$ does not occur in the formula $F[x \mapsto x_0]$ because it has been replaced by
the fixed value $x_0$.  Therefore, the formula
\\[0.2cm]
\hspace*{1.3cm}
$ F[x \mapsto x_0] $
\\[0.2cm]
remains valid after the assignment  ``\texttt{x = h(x);}'' is executed.  After this assignment,
the variable $x$ is set to $h(x_0)$. Therefore, we have
\\[0.2cm]
\hspace*{1.3cm}
$x = h(x_0)$.
\\[0.2cm]
Let us solve this equation for $x_0$.  We find
\\[0.2cm]
\hspace*{1.3cm}
$h^{-1}(x) = x_0$.
\\[0.2cm]
Therefore, after the assignment the formula
\\[0.2cm]
\hspace*{1.3cm}
$ F[x \mapsto x_0] \equiv  F[x \mapsto h^{-1}(x)]$
\\[0.2cm]
is valid and  this is the formula that is written as $F\sigma$ above.

We conclude this discussion with another example.  The unary predicate \textsl{prime} checks whether
its argument is a prime number.  Therefore, $\textsl{prime}(x)$ is true if $x$ is a prime number.
Then we have
\\[0.2cm]
\hspace*{1.3cm}
$\hoare{\textsl{prime}(x)}{x := x + 1;}{\textsl{prime}(x-1)}$.
\\[0.2cm]
The correctness of this Hoare triple should be obvious: If $x$ is a prime and if $x$ is then
incremented by $1$, then afterwards $x-1$ is prime.

\paragraph{Different Forms of Assignments}
Not all assignments can be written in the form ``\texttt{x := h(x);}'' where the function $h$ is invertible.
Often, a constant $c$ is assigned to some variable $x$.  If $x$ does not occur in the precondition
$F$, then we have
\\[0.2cm]
\hspace*{1.3cm}
$ \hoare{F}{x := c;}{F \wedge x = c}. $
\\[0.2cm]
The formula $F$ can be used to restrict the values of other variables occurring in the program under
consideration.

\paragraph{General Form of the Assignment Rule}
In the literature the rule for specifying an assignment is given as
\\[0.2cm]
\hspace*{1.3cm}
$ \hoare{F[x \mapsto t]}{x := t;}{F}. $
\\[0.2cm]
Here, $t$ is an arbitrary term that can contain the variable $x$.  This rule can be read as follows:
\\[0.2cm]
\hspace*{1.3cm}
\begin{minipage}[c]{0.8\linewidth}
``\emph{If the formula $F(t)$ is valid in some state and $t$ is assigned to $x$,
        then after this assignment we have $F(x)$.}''
\end{minipage}
\\[0.2cm]
This rule is obviously correct.  However, it is not very useful because in order to apply this rule
we first have to rewrite the precondition as $F(t)$.  If $t$ is some complex term, this is often
very difficult to do.

\subsection{The Weakening Rule}
If a program fragment $P$ satisfies the specification
\\[0.2cm]
\hspace*{1.3cm}
$ \hoare{F}{P}{G} $
\\[0.2cm]
and if, furthermore, the formula $G$ implies the validity of the formula $H$, that is if
\\[0.2cm]
\hspace*{1.3cm}
$G \rightarrow H$
\\[0.2cm]
holds, then the program fragment $P$ satisfies
\\[0.2cm]
\hspace*{1.3cm}
$\hoare{F}{P}{H}$.
\\[0.2cm]
The reasoning is as follows:  If after executing $P$ we know that $G$
is valid, then, since $G$ implies $H$,  the formula $H$ has to be
valid, too.
Therefore, the  following \emph{verification rule}, which is known as the \emph{weakening rule}, is valid:
\\[0.4cm]
$\bruch{\quad \hoare{F}{P}{G}, \qquad G \rightarrow H \quad}{\hoare{F}{P}{H}}$
\\[0.2cm]
The formul\ae\ written over the fraction line are called the \emph{premisses} and the formula under the
fraction line is called the \emph{conclusion}.   The conclusion and the first premiss  are
Hoare triples, the second premiss is a formula of first order logic.
The interpretation of this rule is that the conclusion is true if the premisses are true.

\subsection{Compound Statements}
If the program fragments $\texttt{P}$ and $\texttt{Q}$ have the specifications
\\[0.2cm]
\hspace*{1.3cm}
$ \hoare{F_1}{P}{G_1}$  \quad and \quad $\hoare{F_2}{Q}{G_2}$
\\[0.2cm]
and if, furthermore, the postcondition $G_1$ implies the precondition $F_2$,
then the composition $\texttt{P;Q}$ of $\texttt{P}$ and $\texttt{Q}$ satisfies the specification
\\[0.2cm]
\hspace*{1.3cm}
$\hoare{F_1}{P;Q}{G_2}$.
\\[0.2cm]
The reasoning is as follows:  If, initially, $F_1$ is satisfied and we execute $P$ then we have
$G_1$ afterwards.  Therefore we also have $F_2$ and if we now execute $Q$ then afterwards we will have
$G_2$.  This chain of thoughts is combined in the following verification rule:
\\[0.4cm]
\hspace*{1.3cm}
$\bruch{\quad\hoare{F_1}{P}{G_1}, \qquad G_1 \rightarrow F_2, \qquad \hoare{F_2}{Q}{G_2}\quad}{\hoare{F_1}{P;Q}{G_2}}
$
\\[0.2cm]
If the formul\ae\ $G_1$ and $F_2$ are identical, then this rule can be simplified as follows:
\\[0.4cm]
\hspace*{1.3cm}
$\bruch{\quad\hoare{F_1}{P}{G_1}, \qquad \hoare{G_1}{Q}{G_2}\quad}{ \hoare{F_1}{P;Q}{G_2}}$

\exampleEng
Let us analyse the program fragment shown in Figure \ref{fig:swap}.
We start our analysis by using the precondition
\\[0.2cm]
\hspace*{1.3cm}
$ \texttt{x} = a \wedge \texttt{y} = b. $
\\[0.2cm]
Here, $a$ and $b$ are two variables that we use to store the initial values of \texttt{x} and
\texttt{y}.  The first assignment yields the Hoare triple
\\[0.2cm]
\hspace*{1.3cm}
$\hoare{\texttt{x} = a \wedge \texttt{y} = b}{x := x - y;}{(\texttt{x} = a \wedge \texttt{y} =  b)\sigma}$
\\[0.2cm]
where $\sigma = [x \mapsto x + y]$. The form of $\sigma$ follows from the fact that the function $x \mapsto x + y$ is the inverse of the
function $x \mapsto x - y$.  If we apply $\sigma$ to the formula $x = a \wedge y = b$
we get
\begin{equation}
  \label{eq:swap1}
 \hoare{\texttt{x} = a \wedge \texttt{y} = b}{x := x - y;}{\texttt{x + y} = a \wedge \texttt{y} = b}.
\end{equation}
The second assignment yields the Hoare triple
\\[0.2cm]
\hspace*{1.3cm}
$ \hoare{\texttt{x + y} = a \wedge \texttt{y} = b}{y := y + x;}{(\texttt{x + y} = a \wedge  \texttt{y} = b)\sigma}$
\\[0.2cm]
where $\sigma = [y \mapsto y - x]$.  The reason is that the function $y \mapsto y - x$ is the inverse of the function $y \mapsto y + x$.
This time, we get
\[ \hoare{\texttt{x + y} = a \wedge \texttt{y} = b}{y := y + x;}{
          \texttt{x + y - x} = a \wedge \texttt{y - x} = b}.
\]
Simplifying the postcondition yields
\begin{equation}
  \label{eq:swap2}
 \hoare{\texttt{x + y} = a \wedge \texttt{y} = b}{y := y + x;}{ \texttt{y} = a \wedge \texttt{y - x} = b}.
\end{equation}
Let us consider the last assignment.  We have
\\[0.2cm]
\hspace*{1.3cm}
$\hoare{\texttt{y} = a \wedge \texttt{y - x} = b}{x := y - x;}{ (\texttt{y} = a \wedge \texttt{y - x} = b)\sigma}$
\\[0.2cm]
where $\sigma = [x \mapsto y - x]$,
since the function $x \mapsto y - x$ is the inverse of the function $x \mapsto y - x$.
This yields
\[ \hoare{\texttt{y} = a \wedge \texttt{y - x} = b}{x := y - x;}{
          \texttt{y} = a \wedge \texttt{y - (y - x)} = b}
\]
Simplifying the postcondition gives
\begin{equation}
  \label{eq:swap3}
  \hoare{\texttt{y} = a \wedge \texttt{y - x} = b}{x := y - x;}{ \texttt{y} = a \wedge \texttt{x} = b}.
\end{equation}
Combining the Hoare triples (\ref{eq:swap1}), (\ref{eq:swap2}) and (\ref{eq:swap3})
we get
\begin{equation}
  \label{eq:swap}
  \hoare{\texttt{x} = a \wedge \texttt{y} = b}{x:=x-y; y:=y+x; x:=y-x;}{
         \texttt{y} = a \wedge \texttt{x} = b}.
\end{equation}
The Hoare triple (\ref{eq:swap}) shows that the program fragment shown in Figure
\ref{fig:swap} swaps the values of the variables $x$ and $y$: If the value of
$x$ is $a$ and $y$ has the value $b$ before the program is executed, then afterwards
$y$ has the value $a$ and $x$ has the value $b$.  The trick shown in Figure
\ref{fig:swap}
can be used to swap variables without using an auxiliary variable.  This is useful because when this
code is compiled into machine language, the resulting code will only use two registers.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    x := x - y;
    y := y + x;
    x := y - x;
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A tricky way to swap variables.}
\label{fig:swap}
\end{figure}

\subsection{Conditional Statements}
In order to compute the effect of a conditional of the form
\\[0.2cm]
\hspace*{1.3cm}
\texttt{if ($B$) \{ P \} else \{  Q \}}
\\[0.2cm]
let us assume that before the conditional statement is executed, the
precondition $F$ is satisfied.   We have to analyse the effect of the program fragments $P$ and $Q$.
The program fragment $P$ is only executed when $B$ is true.  Therefore, the precondition for $P$ is
$F \wedge B$.  On the other hand, the precondition for the program fragment $Q$ is $F \wedge \neg B$,
since $Q$ is only executed if $B$ is false.
Hence, we have the following verification rule:
\begin{equation}
  \label{eq:hoareIf}
  \bruch{\quad\hoare{F \wedge B}{P}{G}, \qquad \hoare{F \wedge \neg B}{Q}{G}\quad}{
              \hoare{F}{if ($B$) P else Q}{G}}
\end{equation}
In this form, the rule is not always applicable.  The reason is that the analysis of the program
fragments \texttt{P} and \texttt{Q} yields Hoare triple of the form
\begin{equation}
  \label{eq:hoareI}
 \hoare{F \wedge B}{P}{G_1} \qquad \mathrm{and} \qquad \hoare{F \wedge \neg B}{Q}{G_2},
\end{equation}
and in general $G_1$ and $G_2$ will be different from each other.  In order to be able to apply the
rule for conditionals we have to find a formula $G$ that is a consequence of $G_1$ and also a
consequence of $G_2$, i.~e.~we want to have
\[ G_1 \rightarrow G \qquad \mathrm{and} \qquad G_2 \rightarrow G. \]
If we find $G$, then the weakening rule  can be applied to conclude the validity of
\[ \hoare{F \wedge B}{P}{G} \qquad \mathrm{and} \qquad \hoare{F \wedge \neg B}{Q}{G},    \]
and this gives us the premisses that are needed for the rule
(\ref{eq:hoareIf}).
\pagebreak

\exampleEng
Let us analyze the following program fragment:
\\[0.2cm]
\hspace*{1.3cm}
\texttt{if (x < y) \{ z := x; \} else \{ z := y; \}}
\\[0.2cm]
We start with the precondition
\\[0.2cm]
\hspace*{1.3cm}
$F = \bigl(\texttt{x} = a \wedge \texttt{y} = b\bigr)$
\\[0.2cm]
and want to show that the execution of the conditional establishes the postcondition
\\[0.2cm]
\hspace*{1.3cm}
$G = \bigl(z = \textsl{min}(a, b)\bigr)$.
\\[0.2cm]
The first assignment ``\texttt{z := x;}'' gives the Hoare triple
\\[0.2cm]
\hspace*{1.3cm}
$\hoare{\texttt{x} = a \wedge \texttt{y} = b \wedge \texttt{x} < \texttt{y}}{z := x}{
          \texttt{x} = a \wedge \texttt{y} = b \wedge \texttt{x} < \texttt{y} \wedge \texttt{z} = \texttt{x}}
$.
\\[0.2cm]
In the same way, the second assignment ``\texttt{z := y}'' yields
\\[0.2cm]
\hspace*{1.3cm}
$\hoare{\texttt{x} = a \wedge \texttt{y} = b \wedge \texttt{x} \geq \texttt{y}}{z := y}{
          \texttt{x} = a \wedge \texttt{y} = b \wedge \texttt{x} \geq \texttt{y} \wedge
          \texttt{z} = \texttt{y}}$.
\\[0.2cm]
Since we have
\\[0.2cm]
\hspace*{1.3cm}
$\texttt{x} = a \wedge \texttt{y} = b \wedge \texttt{x} < \texttt{y} \wedge \texttt{z} = \texttt{x}
   \rightarrow \texttt{z} = \min(a,b)$
\\[0.2cm]
and also
\\[0.2cm]
\hspace*{1.3cm}
$ \texttt{x} = a \wedge \texttt{y} = b \wedge \texttt{x} \geq \texttt{y} \wedge \texttt{z} = \texttt{y}
   \rightarrow \texttt{z} = \min(a,b)
$.
\\[0.2cm]
Using the weakening rule we conclude that
\begin{eqnarray*}
\hoare{\texttt{x} = a \wedge \texttt{y} = b \wedge \texttt{x} < \texttt{y}}{z := x;}{
       \texttt{z} = \min(a,b)} & & \mathrm{and} \\
\hoare{\texttt{x} = a \wedge \texttt{y} = b \wedge \texttt{x} \geq \texttt{y}}{z := y;}{
          \texttt{z} = \min(a,b)}
\end{eqnarray*}
holds.  Now we can apply the rule for the conditional and conclude
that
\\[0.2cm]
$ \hoare{\texttt{x} = a \wedge \texttt{y} = b}{if (x < y) \{ z := x; \} else \{ z := y; \}}{ \texttt{z} = \min(a,b)} $
\\[0.2cm]
holds.  Thus we have shown that the program fragment above computes
the minimum of the numbers $a$ and $b$.

\subsection{Loops}
Finally, let us analyze the effect of a loop of the form
\\[0.2cm]
\hspace*{1.3cm}
\texttt{while ($B$) \{ P \}}
\\[0.2cm]
The important point here is that the postcondition of the $n$-th
execution of the body of the loop $P$ is the precondition of the $(n\!+\!1)$-th
execution of $P$.  Basically this means that the precondition and the
postcondition of $P$ have to be more or less the same.
Hence, this condition is called the \emph{loop invariant}.  Therefore,
the details of the verification rule for \texttt{while} loops are as follows:
\\[0.2cm]
\hspace*{1.3cm}
$\bruch{\hoare{I \wedge B}{P}{I}}{\quad \hoare{I}{while ($B$) \{ P \}}{I \wedge \neg B}\quad}$
\\[0.2cm]
The premiss of this rule expresses the fact that the invariant $I$ remains valid on execution of $P$.
However, since $P$ is only executed as long as $B$ is \texttt{true}, the precondition for $P$ is actually
the formula $I \wedge B$.  The conclusion of the rule says that if the invariant $I$ is true before
the loop is executed, then $I$ will be true after the loop has finished.  This result is intuitive
since every time $P$ is executed $I$ remains valid.  Furthermore, the loop only terminates once $B$
gets \texttt{false}.  Therefore, the postcondition of the loop can be strengthened by adding $\neg B$.

\section{The Euclidean  Algorithm}
In this section we show how the verification rules of the last section can be used to prove the
correctness of a non-trivial program.
We will show that the algorithm shown in Figure \ref{fig:gcd.stlx} on page \pageref{fig:gcd.stlx} is correct.
The procedure shown in this figure implements the
\href{http://en.wikipedia.org/wiki/Euclidean_algorithm}{\emph{Euclidean algorithm}}
to compute the greatest common divisor of two natural numbers.  Our proof is based on the following
property of the function \texttt{gcd}:
\\[0.2cm]
\hspace*{1.3cm}
$\texttt{gcd}(x + y, y) = \texttt{gcd}(x,y) \quad \mbox{for all $x, y \in \mathbb{N}$}$.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    gcd := procedure(x, y) {
        while (x != y) {
            if (x < y) {
                y := y - x;
            } else {
                x := x - y;
            }
        }
        return x;
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{The Euclidean Algorithm to compute the greatest common divisor.}
\label{fig:gcd.stlx}
\end{figure}

\subsection{Correctness Proof of the Euclidean Algorithm}
To start our correctness proof we formulate the invariant of the \texttt{while} loop.
Let us define
\\[0.2cm]
\hspace*{1.3cm}
$ I := \bigl(x > 0 \wedge y > 0 \wedge \texttt{gcd}(x,y) = \texttt{gcd}(a,b) \bigr)$
\\[0.2cm]
In this formula we have defined the initial values of $x$ and $y$ as $a$ and $b$.
In order to establish the invariant at the beginning we have to ensure that the function
\texttt{gcd} is only called with positive natural numbers.  If we denote these numbers as
$a$ and $b$, then the invariant $I$ is valid initially.  The reason is that $x = a$ and $y = b$
implies $\texttt{gcd}(x,y) = \texttt{gcd}(a,b)$.

In order to prove that the invariant $I$ is maintained in the loop we formulate the Hoare triples
for both alternatives of the conditional.  For the first conditional we know that
\\[0.2cm]
\hspace*{1.3cm}
$\hoare{I \wedge x \not= y \wedge x < y}{y := y - x;}{(I \wedge x \not= y \wedge x < y)\sigma}$
\\[0.2cm]
holds, where $\sigma$ is defined as $\sigma = [y \mapsto y + x]$.  Here, the condition $x \not= y$
is the condition controlling the execution of the
\texttt{while} loop and the condition $x < y$ is the condition of the \texttt{if} conditional.
We rewrite the formula $(I \wedge x \not= y \wedge x < y)\sigma$:
\begin{eqnarray*}
 &                 & \bigl(I \wedge x \not= y \wedge x < y\bigr)\sigma \\
 & \leftrightarrow & \bigl(I \wedge x < y\bigr)\sigma
                     \qquad\qquad \mbox{because $x < y$ implies $x \not= y$} \\
 & \leftrightarrow & \bigl(x > 0 \wedge y > 0 \wedge \texttt{gcd}(x,y) = \texttt{gcd}(a,b) \wedge
                     x < y\bigr)[y \mapsto y + x] \\
 & \leftrightarrow & x > 0 \wedge y + x > 0 \wedge \texttt{gcd}(x,y+x) = \texttt{gcd}(a,b)
                     \wedge x < y + x \\
 & \leftrightarrow & x > 0 \wedge y + x > 0 \wedge \texttt{gcd}(x,y) = \texttt{gcd}(a,b) \wedge 0 < y
\end{eqnarray*}
In the last step we have used the formula
\\[0.2cm]
\hspace*{1.3cm}
$ \texttt{gcd}(x,y+x) = \texttt{gcd}(x,y) $
\\[0.2cm]
and we have simplified the inequality $x < y + x$ as $0 < y$.
The last formula implies
\\[0.2cm]
\hspace*{1.3cm}
$ x > 0 \wedge y > 0 \wedge \texttt{gcd}(x,y) = \texttt{gcd}(a,b) $.
\\[0.2cm]
However, this is precisely the invariant $I$.  Therefore we have shown that
\begin{equation}
  \label{eq:if1}
  \hoare{I \wedge x \not= y \wedge x < y}{y := y - x;}{I}
\end{equation}
holds.  Next, let us consider the second alternative of the \texttt{if} conditional.  We have
\\[0.2cm]
\hspace*{1.3cm}
$\hoare{I \wedge x \not= y \wedge x \geq y}{x := x - y;}{(I \wedge x \not= y \wedge x \geq y)\sigma}$
\\[0.2cm]
where $\sigma = [x \mapsto x + y]$. The expression $(I \wedge x \not= y \wedge x \geq y)\sigma$ is rewritten as follows:
\begin{eqnarray*}
 &   & \bigl(I \wedge x \not= y \wedge x \geq y\bigr)\sigma \\
 & \leftrightarrow & \bigl(I \wedge x > y \bigr)\sigma \\
 & \leftrightarrow & \bigl(x > 0 \wedge y > 0 \wedge \texttt{gcd}(x,y) = \texttt{gcd}(a,b) \wedge
             x > y \bigr)[x \mapsto x + y] \\
 & \leftrightarrow & x + y > 0 \wedge y > 0 \wedge \texttt{gcd}(x+y,y) = \texttt{gcd}(a,b)
       \wedge x + y > y  \\
 & \leftrightarrow & x + y > 0 \wedge y > 0 \wedge \texttt{gcd}(x,y) = \texttt{gcd}(a,b)
       \wedge x > 0
\end{eqnarray*}
The last formula implies that
\\[0.2cm]
\hspace*{1.3cm}
$ x > 0 \wedge y > 0 \wedge \texttt{gcd}(x,y) = \texttt{gcd}(a,b). $
\\[0.2cm]
holds.  Again, this is our invariant $I$.  Therefore we have shown that
\begin{equation}
  \label{eq:if2}
  \hoare{I \wedge x \not= y \wedge x \geq y}{x := x - y;}{I}
\end{equation}
holds.  If we use the Hoare triples (\ref{eq:if1}) and (\ref{eq:if2}) as premisses
for the rule for conditionals we have shown that
\\[0.2cm]
\hspace*{1.3cm}
$  \hoare{I \wedge x \not= y}{if (x < y) \{ y := y - x; \} else \{  x := x - y; \}}{I} $
\\[0.2cm]
holds.  Now the verification rule for \texttt{while} loops yields

\noindent
\hspace*{1.3cm}
$\{ I \}$
\\[0.1cm]
\hspace*{2.2cm}
\texttt{while (x != y ) \{} \\[0.1cm]
\hspace*{3.2cm}
         \texttt{if (x < y) \{ y := y - x; \} else \{ x := x - y;\}}
\\[0.1cm]
\hspace*{2.2cm}
\texttt{\}} \quad
\\[0.1cm]
\hspace*{1.3cm}
$\{ I \wedge x = y \}$.
\\[0.2cm]
Expanding the invariant $I$ in the formula $I \wedge x = y$ shows that the postcondition of the
\texttt{while} loop is given as
\\[0.2cm]
\hspace*{1.3cm}
$x > 0 \wedge y > 0 \wedge \texttt{gcd}(x,y) = \texttt{gcd}(a,b) \wedge x = y$.
\\[0.2cm]
Now the correctness of the Euclidean algorithm can be established as follows:
\begin{eqnarray*}
&             &  x > 0 \wedge y > 0 \wedge \texttt{gcd}(x,y) = \texttt{gcd}(a,b) \wedge x = y \\
& \Rightarrow & \texttt{gcd}(x,y) = \texttt{gcd}(a,b) \wedge x = y \\
& \Rightarrow & \texttt{gcd}(x,x) = \texttt{gcd}(a,b)  \\
& \Rightarrow & x = \texttt{gcd}(a,b) \qquad\qquad \mathrm{because} \quad \texttt{gcd}(x,x) = x.
\end{eqnarray*}
All in all we have shown the following: If the \texttt{while} loop terminates, then
the variable $x$ will be set to the greatest common divisor of $a$ and $b$, where $a$ and $b$ are
the initial values of the variables $x$ and $y$.  In order to finish our correctness proof we have
to show that the \texttt{while} loop does indeed terminate for all choices of $a$ and $b$.
To this end let us define the variable $s$ as follows:
\\[0.2cm]
\hspace*{1.3cm}
$ s := x + y. $
\\[0.2cm]
The variables $x$ and $y$ are natural numbers.  Therefore $s$ is a natural number, too.
Every iteration of the loop reduces the number $s$: either $x$ is subtracted from $s$
or $y$ is subtracted from  $s$ and the invariant $I$ shows that both $x$ and $y$ are
positive.  Therefore, if the \texttt{while} loop would run forever, at some point $s$ would get
negative.  Since $s$ can not be negative, the loop must terminate.
Hence we have shown the correctness of the Euclidean  algorithm.
\pagebreak

\exerciseEng
Show that the function $\texttt{power}(x,y)$ that is defined in Figure
\ref{fig:power-iterative.stlx} does compute $x^y$, i.~e.~show that $\texttt{power}(x,y) = x^y$
for all natural numbers $x$ and $y$.

\begin{figure}[!h]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 1.3cm,
                  xrightmargin  = 1.3cm,
                ]
    power := procedure(x, y) {
        r := 1;
        while (y > 0) {
            if (y % 2 == 1) {
                r := r * x;
            }
            x := x * x;
            y := y \ 2;
        }
        return r;
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A program to compute $x^y$ iteratively.}
\label{fig:power-iterative.stlx}
\end{figure}

\noindent
\textbf{Hints}:
\begin{enumerate}
\item If the initial values of $x$ and $y$ are called $a$ and $b$,
      then an invariant for the \texttt{while} loop is given as
      \\[0.2cm]
      \hspace*{1.3cm}
      $I := \bigl(r \cdot x^y = a^b\bigr)$.
\item The verification rule for the conditional without \texttt{else} is given as
      \\[0.4cm]
      \hspace*{1.3cm}
      $\bruch{\quad\hoare{F \wedge B}{P}{G}, \qquad F \wedge \neg B \rightarrow G\quad}{
                     \hoare{F}{if ($B$) \{ P \}}{G}}
      $
      \\[0.2cm]
      This rule is interpreted as follows:
      \begin{enumerate}
      \item If both the precondition $F$ and the condition $B$ is valid, then execution of the
            program fragment $P$ has to establish the validity of the postcondition $G$.
      \item If the precondition $F$ is valid but we have $\neg B$, then this must imply the postcondition
            $G$.
      \end{enumerate}
\end{enumerate}

\remark
Proving the correctness of a nontrivial program is very tedious.
Therefore, various attempts have been made to automate the task.  For
example, \href{http://www.key-project.org/download/hoare/}{\emph{KeY Hoare}}
is a tool that can be used to verify the correctness of programs.  It is based on
Hoare calculus.

\section{Symbolic  Program Execution}
The last section has shown that using Hoare logic to verify a program can be quite difficult.
There is another method to prove the correctness of imperative programs.  This method is called
\emph{symbolic program execution}.  Let us demonstrate this method.  Consider the program
shown in Figure \ref{fig:power-iterative-annotated.stlx}.

\begin{figure}[!h]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 1.3cm,
                  xrightmargin  = 1.3cm,
                  codes         = {\catcode`_=8\catcode`$=3},
                  commandchars  = \\\{\},
                ]
    power := procedure(x$_0$, y$_0$) \{
        r$_0$ := 1;
        while (y$_n$ > 0) \{
            if (y$_n$ % 2 == 1) \{
                r$_{n+1}$ := r$_n$ * x$_n$;
            \}
            x$_{n+1}$ := x$_n$ * x$_n$;
            y$_{n+1}$ := y$_n$ \symbol{92} 2;
        \}
        return r$_N$;
    \};
\end{Verbatim}
\vspace*{-0.3cm}
\caption{An annotated programm to compute powers.}
\label{fig:power-iterative-annotated.stlx}
\end{figure} % $

The main difference between a mathematical formula and a program is that in a formula all
occurrences of a variable refer to the same value.   This is different in a program because the
variables change their values dynamically.  In order to deal with this property of program variables
we have to be able to distinguish the different occurrences of a variable.  To this end,  we
index the program variables.
When doing this we have to be aware of the fact that the same occurrence of a program variable can
still denote different values if the variable occurs inside  a loop.  In this case we have to index
the variables in a way that the index includes a counter that counts the number of loop iterations.
For concreteness, consider the  program shown in
Figure \ref{fig:power-iterative-annotated.stlx}.
Here, in line 5 the variable \texttt{r} has the index $n$ on the right side of the assignment,
while it has the index $r_{n+1}$ on the left side of the assignment in line 5.  Here, $n$ denotes
the number of times the \texttt{while} loop has been iterated.
After the loop in line 10 the variable is indexed as
$\texttt{r}_N$, where $N$ denotes the total number of loop iterations.
We show the correctness of the given program next.  Let us define
\\[0.2cm]
\hspace*{1.3cm}
$ a := x_0, \quad b := y_0$.
\\[0.2cm]
We show, that the \texttt{while} loop satisfies the invariant
\begin{equation}
  \label{eq:powerInv}
   r_n \cdot x_n^{y_n} = a^b.
\end{equation}
This claim is proven by induction on the number of loop iterations.
\begin{enumerate}
\item[B.C.] $n=0$: Since we have $r_0 = 1$, $x_0 = a$, and $y_0 = b$ we have
            \\[0.2cm]
            \hspace*{1.3cm}
            $r_n \cdot x_n^{y_n} = r_0 \cdot x_0^{y_0} = 1 \cdot a^{b} = a^b$.
\item[I.S.] $n \mapsto n + 1$:  We need a case distinction with respect to $y \mod 2$:
            \begin{enumerate}
            \item $y_n \mod 2 = 1$.  Then we have $y_{n} = 2 \cdot (y_n\symbol{92}2) + 1$ and
                  $r_{n+1} = r_n \cdot x_n$.  Hence
                  \begin{eqnarray*}
                      &   & r_{n+1} \cdot x_{n+1}^{y_{n+1}} \\[0.2cm]
                      & = & (r_{n} \cdot x_n) \cdot (x_{n} \cdot x_{n})^{y_{n}\symbol{92}2} \\[0.2cm]
                      & = & r_{n} \cdot x_n^{2 \cdot (y_{n}\symbol{92}2) + 1} \\[0.2cm]
                      & = & r_{n} \cdot x_n^{y_n} \\
                      & \stackrel{i.h.}{=} & a^{b}
                  \end{eqnarray*}

            \item $y_n \mod 2 = 0$.  Then we have $y_{n} = 2 \cdot (y_n\symbol{92}2)$ and $r_{n+1} = r_n$.
                  Therefore
                  \begin{eqnarray*}
                      &   & r_{n+1} \cdot x_{n+1}^{y_{n+1}} \\[0.2cm]
                      & = & r_{n} \cdot (x_{n} \cdot x_{n})^{y_{n}\symbol{92}2} \\[0.2cm]
                      & = & r_{n} \cdot x_n^{2 \cdot (y_{n} \symbol{92} 2)} \\[0.2cm]
                      & = & r_{n} \cdot x_n^{y_n} \\
                      & \stackrel{i.h.}{=} & a^{b}
                  \end{eqnarray*}
            \end{enumerate}
\end{enumerate}
This shows the validity of the equation (\ref{eq:powerInv}).   If the \texttt{while} loop
terminates, we must have $y_N = 0$.  If $n=N$, then equation (\ref{eq:powerInv}) yields:
\\[0.2cm]
\hspace*{1.3cm}
$r_N \cdot x_N^{y_N} = x_0^{y_0}
 \;\Longleftrightarrow\; r_N \cdot x_N^{0}   = a^b
 \;\Longleftrightarrow\;  r_N \cdot 1         = a^b
 \;\Longleftrightarrow\;  r_N                 = a^b
$
\\[0.2cm]
This shows $r_N = a^b$ and since we already know that the
\texttt{while} loop terminates, we have proven that
$\texttt{power}(a,b) =a^b$.

\exerciseEng
Use the method of symbolic program execution to prove the correctness of the implementation of the
Euclidean algorithm that is shown in Figure \ref{fig:gcd.stlx}.  During the proof you should make
use of the fact that for all positive natural numbers $a$ and $b$ the equation
\\[0.2cm]
\hspace*{1.3cm}
$\mathtt{gcd}(a, b) = \mathtt{gcd}(a \,\texttt{\%}\, b, b)$
\\[0.2cm]
is valid.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    gcd := procedure(a, b) {
        while (b != 0) {
            [a, b] := [b, a % b];
        }
        return a;
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{An efficient version of the Euclidean algorithm.}
\label{fig:gcd.stlx}
\end{figure}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "logik"
%%% End:


\subsection{Notations}
  Vectors will be written in column form and denoted by boldface lower-case letters.
  The set of integers $\{\ell,\ldots,k\}$ is denoted by $[\ell,k]$.
  For a non-negative integer $a$, let $\texttt{wt}(a)$ be the Hamming weight of its binary expansion. We denote the set of residue classes modulo $p$ by $\Z_p$ and the class representatives of $\Z_p$ are taken from the half-open interval $[-p/2, p/2)$.

\subsection{Comparison of integers with finite fields operations}
  Let $\S$ be a totally ordered set with a binary relation $<$.
  For any $x,y \in \S$, we can define the less-than and the equality functions as follows.
  \begin{align*}
    \LT_\S(x,y) =
    \begin{cases}
      1, & \text{if } x < y; \\
      0, & \text{if } x \ge y, \\
    \end{cases}
    \\
    \EQ_\S(x,y) =
    \begin{cases}
      1, & \text{if } x = y; \\
      0, & \text{if } x \neq y. \\
    \end{cases}
  \end{align*}
  %In our case, $\S$ is a set of consecutive integers.

\subsubsection{Functions over finite fields}\label{subsec:funcff}
The map defined by $\princhar: x \mapsto x^{p^d-1}$ from $\F_{p^d}$ to the binary set $\{0,1\}$ is called the \emph{principal character}.
According to Euler's theorem, it returns $1$ if $x$ is non-zero and $0$ otherwise.
%It can thus be used to compute the equality function:
%\begin{align*}
%  \EQ_{\F_{p^d}}(x,y) = 1 - \princhar (x-y).
%\end{align*}
%Moreover, note that since:
%\begin{align}\label{eq:exp_frob}
%  a^{p^d-1} = a^{(p-1)(p^{d-1} + \dots + 1)} = \prod_{i=0}^{d-1} \left(a^{p-1}\right)^{p^i},
%\end{align}
%$\chi$ can be computed with Frobenius maps ($x \mapsto x^p$) and multiplications.
Using the principal character, every function from $\F_{p^d}^l$ to $\F_{p^d}$ can be interpolated by a unique polynomial according to the following well-know lemma.
\begin{lemma}\label{lem:interpolation}
  Every function $f: \F_{p^d}^l \rightarrow \F_{p^d}$ is a polynomial function represented by a unique polynomial $P_f(X_1,\dots,X_{l})$ of degree at most $p^d - 1$ in each variable.
  In particular,
  \begin{align*}
    P_f(X_1,\dots,X_{l}) = \sum_{\va \in \F^l_{p^d}} f(\va) \prod_{i=1}^{l} \left(1 - \princhar(X_i - a_i)\right)\,.
  \end{align*}
  where $a_i$ is the $i$th coordinate of vector $\va$.
\end{lemma}

\subsubsection{Comparison of integers}
  Let $\F_{p^d} = \F_p[X]/\ideal{f(X)}$ for some irreducible monic polynomial $f(X)$ of degree $d$.
  Let $d'\leq d$ and $\S \subseteq [0,p^{d'}-1]$, we can map $\S$ into $\F_{p^d}$ by using the decomposition of integers in base $p$:
  $$\begin{array}{cccc}
      \iota_p : & \S & \rightarrow & \F_{p^d}\,, \\
              & \displaystyle\sum_{i=0}^{d'-1}a_ip^i & \mapsto & \displaystyle\sum_{i=0}^{d'-1}a_i X^{i-1}\,.
    \end{array}$$
  Note that the map $\iota_p$ is injective and gives a one-to-one correspondence between $\S$ and $\F_{p^{d}}$ when $d'=d$ and $\S = [0,p^d-1]$.
  Therefore, we identify integers belonging to $\S$ with their image by $\iota_p$ and thus omit $\iota_p$ when the situation is clear from the context.

  Let $a,b \in \S$ be two integers to be compared and $\sum_{i=0}^{d'-1} a_i X^i$ and $\sum_{i=0}^{d'-1} b_i X^i$ with $a_i, b_i \in \F_p$ are their respective encodings into $\F_{p^d}$.
  The order of the set $\S$ induces a polynomial function in $\F_{p^d}$, which can be interpolated by Lemma~\ref{lem:interpolation}.
  However, since $\LT_\S(0,y) = 1$ for any non-zero $y \in \F_{p^d}$ and zero otherwise, we obtain $\LT_\S(0,y) = \chi(y)$.
  Hence, the total degree of the interpolation polynomial is at least $p^d-1$,
  which might be prohibitive in practice.

  Tan et al.~\cite{TLWRK20} proposed an alternative approach where $\S = [0,p-1]$.
  If input integers $a$ and $b$ belong to $\S$, the result of $\LT_\S$(a,b) is computed with its interpolation polynomial over $\F_p$.
  If $a,b$ are larger, e.g. $a,b \in [0,p^{d'-1}]$, they are encoded into $\F_{p^d}$ as above, but their comparison is performed via the lexicographic order defined on $\F_p^{d'}$.
  This method is based on the extraction of coefficients $a_i, b_i \in \F_p$ thanks to the following result from the theory of finite fields (see \cite[Theorem 2.24]{LN86} for the proof).
  \begin{lemma}\label{lem:extraction}
    The linear transformations from $\F_{p^d}$ to $\F_p$ are exactly the mappings $L_{\alpha}(x) = \Tr_{\F_{p^d}/\F_p}(\alpha x)$ for some $\alpha \in \F_{p^d}$.
    Furthermore, $L_{\alpha} \ne L_{\beta}$ if $\alpha \ne \beta$.
  \end{lemma}
  This lemma implies that for any $i \in [0,d'-1]$ there exist $\alpha_i \in \F_{p^d}$ such that $L_{\alpha_i}(a) = a_i$ for any $a$ from the vector subspace $\F_p^{d'}$ of $\F_{p^d}$.
  Such $\alpha_i$'s can be computed by solving the following system of equations over $\F_{p^d}$
  \begin{align*}
    \mX \mA
    =
    \mI_{d}
  \end{align*}
  where
  \begin{align*}
  \mX &= \begin{pmatrix}
      1       & 1       & \dots   & 1             \\
      x       & x^p     & \dots   & x^{p^{d-1}}   \\
      \vdots  & \vdots  & \ddots  & \vdots        \\
      x^{d-1}     & x^{(d-1)p}    & \dots   & x^{(d-1)p^{d-1}}  \\
    \end{pmatrix}\,,
    \\
    \mA &= \begin{pmatrix}
      \alpha_0      & \alpha_1      & \dots   & \alpha_{d-1}      \\
      \alpha_0^{p}  & \alpha_1^{p}  & \dots   & \alpha_{d-1}^{p}  \\
      \vdots        & \vdots        & \ddots  & \vdots            \\
      \alpha_0^{p^{d-1}}  & \alpha_1^{p^{d-1}}  & \dots   & \alpha_{d-1}^{p^{d-1}}  \\
    \end{pmatrix}
  \end{align*}
  and $\mI_d \in \F_{p^d}^{d \times d}$ is the identity matrix.
  Hence, the $i$th column of $\inv{\mX}$ contain the powers $\alpha_i, \alpha_i^p, \dots, \alpha_i^{p^{d-1}}$, which define the linear map $L_{\alpha_i}$.

  Given the input encodings $\sum_{i=0}^{d'-1} a_i X^i$ and $\sum_{i=0}^{d'-1} b_i X^i$, we can extract and then compare their vectors of coefficients $\bm{a} = (a_0,a_1,\ldots,a_{d'-1})$ and $\bm{b} = (b_0,b_1,\ldots,b_{d'-1}) \in \F_p^{d'}$ using the lexicographical order $\bm{<}$ on $\F_{p}^{d'}$ defined by
   \begin{align*}
      \bm{a} \bm{<} \bm{b} \Leftrightarrow \exists i\in[0,d'-1] \text{ such that } & a_i < b_i \text{ and } \\
       & a_j = b_j ~~ \forall j > i \,.
    \end{align*}
    The corresponding less-than function is equal to
    \begin{align*}
      \LT_{\S^{d'}}(\bm{a}, \bm{b}) = \sum_{i=0}^{d'-1} \LT_{\S}(a_{i}, b_{i}) \prod_{j=i+1}^{d'-1} \EQ_{\S}(a_{j}, b_{j})\,,
    \end{align*}
    whereas the equality function is defined by
    \begin{align*}
      \EQ_{\S^{d'}}(\bm{a}, \bm{b}) = \prod_{i=0}^{d'-1} \EQ_{\S}(a_{i}, b_{i})\,,
    \end{align*}
    Notice that the above construction is generic for any set $\S$ embedded into $\F_p$.
    For example, if $\S = [0,s-1]$ for some $s < p$, then one can encode input integers via decomposition in base $s$ and compare them using $\LT_{\S^{d'}}$.
  %This function requires $d'$ evaluations of $\LT_{\F_{p}}$ which has degree at most $p-1$, $d'-1$ evaluations of $\EQ_{\F_{p}}$ which has also degree $p-1$ and $2d'-1$ additional multiplications.
  %Thus, if we ignore the complexity of digit extraction, the total complexity of comparing elements of $\F_{p}^{d'}$ in terms of multiplications is $O(d'(p-1))$.

\subsubsection{Comparison of large integers}\label{sec:comparison_of_large_integers}
When the size of input integers exceeds $|\S|^d$, we can decompose integers in base $|\S|^{d'}$ and then compare their vectors of digits using the lexicographical order $\bm{<}$ on $\left(\F_{p}^{d'}\right)^l$, for some $d' \le d$.
In fact, we compute two lexicographical orders on top of each other.

Let $a,b \in [0, |\S|^{ld'}-1]$ be input integers.
We represent an integer $a = \sum_{i=0}^l a_i |\S|^{id'}$ by the vector $\va=(\bm{a}_0,\bm{a}_1,\ldots,\bm{a}_{l-1}) \in \left(\F_{p}^{d'}\right)^l$ of its digits of length $l$.
The comparison of two integers $a$ and $b$ is thus equivalent to the comparison of their vector of digits $\va=(\bm{a}_0,\bm{a}_1,\ldots,\bm{a}_{l-1})$ and $\vb=(\bm{b}_0,\bm{b}_1,\ldots,\bm{b}_{l-1})$ using the lexicographical order $\bm{<}$ on $\left(\F_{p}^{d'}\right)^l$ defined as follows
    \begin{align*}
      \va \bm{<} \vb \Leftrightarrow \exists i\in[0,l-1] \text{ such that } & \bm{a}_i < \bm{b}_i \text{ and } \\
      & \bm{a}_j = \bm{b}_j ~~ \forall j > i\,.
    \end{align*}
  As done in~\cite{TLWRK20}, we can employ $\EQ_{\S^{d'}}$ and $\LT_{\S^{d'}}$ to compute the corresponding less-than function $\LT(\va, \vb)$ as follows
  \begin{align}\label{eq:general_lex_order}
    \LT(\va, \vb) = \sum_{i=0}^{l-1} \LT_{\S^{d'}}(\bm{a}_{i}, \bm{b}_{i}) \prod_{j=i+1}^{l-1} \EQ_{\S^{d'}}(\bm{a}_{j}, \bm{b}_{j}).
  \end{align}
  %Notice that the multiplicative depth of this function depends essentially of the products of the equality functions.
  %In fact, these products compare subvectors $\va_i = (\bm{a}_i, \bm{a}_{i+1},\dots,\bm{a}_{k-1})$ and $\vb_i = (\bm{b}_i, \bm{b}_{i+1},\dots,\bm{b}_{k-1})$ for $i \in [1,l-1]$.
  %Thus, we can rewrite $\LT$ as:
  %\begin{align}\label{eq:general_lex_order}
  %  \LT(\va, \vb) = \sum_{i=0}^{k-1} \LT_{\F_{p}^{d'}}(\bm{a}_{i},\bm{b}_{i}) \EQ_{\F_{p}^{d'}}(\va_{i+1}, \vb_{i+1})
  %\end{align}
  %with the equality function $\EQ_{\F_{p}^{d'}}(\va_{i+1}, \vb_{i+1})$ that returns $1$ if $\va_{i+1} = \vb_{i+1}$ and $0$ otherwise.
  % As shown in~\todo{cite our work}, this function can be realized by a constant-depth circuit in the following way.
  % \begin{align}\label{eq:rand_eq_circuit}
  %   \EQ_{\F_\fieldcard, e}(\vx_{i+1},\vy_{i+1}) = 1 - \princhar_{\fieldcard^e}\left(\sum_{j=i+1}^{\ell-1} r_j (x_j - y_j)\right)
  % \end{align}
  % where $r_j$ are uniformly random elements from $\F_{\fieldcard^e}$.
  % This circuit is false-biased with error probability $\fieldcard^{-e}$.
  % We can compute all $\EQ_{\F_\fieldcard, e}(\vx_{i+1},\vy_{i+1})$ using the same number of multiplications as for the single equality using Algorithm~\ref{alg:vector_equalities_circuit}.\todo{What is the complexity?}

%If $\S$ is a complete set of representatives of a finite field $\F_{p^d}$, then the equality function can be easily realized using the principal character of $\F_{p^d}$, namely $\EQ_\S(x,y) = 1 - \princhar_{p^d}(x-y)$.
% Since this function is independent of the choice of $\S$, we can write
% \begin{align*}
%   \EQ_{\F_{p^d}}(x,y) = 1 - \princhar_\fieldcard(x-y).
% \end{align*}
% Unfortunately, the comparison function is not as simple and we have to rely on Lagrange interpolation (Lemma \ref{lem:interpolation}) to compute it. Yet, there are two different ways to evaluate it: either interpolate $\LT_\S$ as a bivariate function over $\S^2$  -- i.e. compute $\LT_\S(x,y)$ -- or transform it as a univariate function in $z=x-y$ -- i.e. compute $\LT_\S(x-y,0)$.

% While the second approach might seems simpler, it requires nonetheless to be able to distinguish between ``postive'' and ``negative'' values. This means that if $\S = [0,p']$ for some $p'\geq 1$, since the values of $z = x-y$ can range within the interval $[-p',p']$, it requires to use a plaintext modulus $p\geq 2p'+1$ while being only able to use ``half'' of it.

\subsection{Homomorphic Encryption}
We are interested in homomorphic encryption schemes that support SIMD operations on their plaintexts.
This section aims at giving the necessary background regarding these schemes.

\subsubsection{Cyclotomic fields and Chinese Remainder Theorem}\label{subsec:crt}

Let $m$ be a positive integer and $n = \varphi(m)$ where $\varphi$ is Euler's totient function.
Let $\mathcal{K} = \Q(\zeta_{m})$ be the cyclotomic number field constructed by adjoining a primitive $m$-th root of unity $\zeta_{m}\in\C$ to the field of rational numbers.
The ring of integers of $\mathcal{K}$, denoted by $\intring$, is isomorphic to $\Z[X]/\ideal{\Phi_m(X)}$ where $\Phi_m(X)$ is the $m$-th cyclotomic polynomial.
Let $p>1$ be a prime number coprime to $m$, then $\Phi_m(X)$ splits modulo $p$ into $\ell$ irreducible factors of same degree $d$, i.e. $\Phi_m(X) = F_1(X)\cdots F_\ell(X) \bmod p$.
The degree $d$ is actually the order of $p$ modulo $m$, and $\ell = n/d$.
The \ac{CRT} states that in this case the following ring isomorphism holds:
\begin{align*}
  \intring_p &= \Z_p[X]/\ideal{\Phi_m(X)} \nonumber \\
  & \cong \Z_p[X]/\ideal{F_1(X)} \times \ldots \times \Z_p[X]/\ideal{F_{\ell}(X)}
\end{align*}
For each $i \in [1,\ell]$ the quotient ring $\Z_p[X]/\ideal{F_i(X)}$ is isomorphic to the finite field $\F_{p^d}$.
Hence, the above isomorphism can be rewritten as $\intring_p \cong \F_{p^d}^\ell$.
We call every copy of $\F_{p^d}$ in this direct product a \emph{slot}.
Therefore, every element of $\intring_p$ contains $\ell$ slots, which implies that an array of $\ell$ independent $\F_{p^d}$-elements can be encoded as a unique element of $\intring_p$.
The slot isomorphic to $\Z_p[X]/\ideal{F_i(X)}$ is referred to as the \emph{$i$th} slot.

Additions and multiplications of $\intring_p$-elements results in the corresponding coefficient-wise operations of their respective slots.
In other words, each ring operation on $\intring_p$ is applied to every slot in parallel, which resembles the Single-Instruction Multiple-Data (SIMD) instructions used in parallel computing.
Therefore, the above encoding method from $\F_{p^d}^\ell$ to $\intring_p$ is often called the \emph{SIMD packing}.

%Using multiplication, we can easily define a projection map $\proj_i$ on $\intring_p$ that sends $a \in \intring_p$ encoding slots $(m_0, \dots, m_{\ell-1})$ to $\pi_i(a)$ encoding $(0, \dots, m_i, \dots, 0)$.
%In particular, $\proj_i(a) = a g_i$, where $g_i \in \intring_t$ encodes $(0 \dots, 1, \dots, 0)$.
%We can generalize this projection for any $I \subseteq \{1,\dots,\ell\}$ to $\proj_I(a) = a g_I$ with $g_I \in \intring_p$ encoding $1$ in the SIMD slots indexed by $I$.\newline

%The field $\numfield = \Q(\zeta_{m})$ is a Galois extension and its Galois group $\mathcal{G} = \Gal{(\numfield/\Q)}$ is isomorphic to $\Z_m^\times$  through: $i \mapsto (\sigma_i: X \mapsto X^i)$ where $i \in \Z_m^\times$.
%The automorphism $\sigma_p$ corresponding to $p$ is called \emph{the Frobenius automorphism} and generates the Galois group $\Gal{(\F_{p^d}/\F_p)}$ of each slot.
%This means that $\mathcal{F} = \ideal{\sigma_p} \subset \mathcal{G}$ partitions the roots of $\Phi_m$  into $\ell$ sets $S_i$ of $d$ elements, each set corresponding to the roots of a factor $F_i$ over $\C$.
%Therefore, the group $\mathcal{H} = \mathcal{G}/\mathcal{F}$ acts transitively on a set of representatives $\bar{S}_i$ of each $S_i$ and thus maps $\bar{S}_i$ to $\bar{S}_j$.
%In other words, the elements of $\mathcal{H}$ permute the SIMD slots.
%However, the order of $\mathcal{H}$ is $n/d = \ell$, which is less than $\ell!$, the number of all possible permutations of the $\ell$ SIMD slots.
%Nonetheless, it was shown in~\cite{GHS12} that every permutation of SIMD slots can be realized by combination of automorphisms from $\mathcal{H}$, projection maps and additions.

The HE schemes that support SIMD packing and \emph{exact} computations over encrypted data include $\BGV$~\cite{BGV12} and $\FV$~\cite{FV12}.
These schemes have a common framework described below.

\subsubsection{Basic setup}

Let $\lambda$ be the security level of an HE scheme.
Let $L$ be the maximal multiplicative depth of homomorphic circuits we want to evaluate.
Let $d$ be the order of the plaintext modulus $p$ modulo the order $m$ of $\intring$.
Assume that the plaintext space $\intring_p$ has $\slots$ SIMD slots, i.e. $\intring_p \cong \F^\ell_{p^d}$.
% For a vector $\va \in \F^k_{p^d}$, we denote the plaintext encoding of $\va$ by $\pt(\va)$.
The basic part of any HE schemes consists of key generation, encryption and decryption algorithms.

$\KeyGen(1^\lambda, 1^L) \rightarrow (\sk, \pk)$. Given $\lambda$ and $L$, this function outputs the secret key $\sk$ and the public key $\pk$.
%Note that the public key contains special key-switching keys that help to transform ciphertexts encrypted under other secret keys back to ciphertexts encrypted under $\sk$.

$\Encrypt(\pt \in \intring_p, \pk) \rightarrow \ct$. The encryption algorithm takes a plaintext $\pt$ and the public key $\pk$ and outputs a ciphertext $\ct$.

$\Decrypt(\ct, \sk) \rightarrow \pt$. The decryption algorithm takes a ciphertext $\ct$ and the secret key $\sk$ and returns a plaintext $\pt$.
For freshly encrypted ciphertexts, the decryption correctness means that $\Decrypt(\Encrypt(\pt, \pk), \sk) = \pt$.

\subsubsection{Homomorphic operations}

The homomorphic addition (multiplication) algorithm takes two input ciphertexts $\ct_1$ and $\ct_2$ encrypting plaintexts $\pt_1$ and $\pt_2$ respectively.
It outputs a ciphertext $\ct$ that encrypts the sum (product) of these plaintexts in the ring $\intring_p$.
It implies that homomorphic addition (multiplication) sums (multiplies) respective SIMD slots of $\pt_1$ and $\pt_2$.
Similar operations between ciphertexts and plaintexts are defined as well.

%As shown in Section~\ref{subsec:crt}, the projection map $\proj_I$ can select the SIMD slots indexed by a set $I \subseteq \{0,\dots,\slots-1\}$ and set the rest to zero.
%This functionality is homomorphically realized by the $\Select$ function.

%$\Select(\ct, I) = \MulPlain(\ct, \pt(\1_I)) \rightarrow \ct'$ where $\1_I$ is a vector having $1$'s in the coordinates indexed by a set $I$ and zeros everywhere else.
%Given a ciphertext $\ct$ encrypting SIMD slots $\vm = (m_0,m_1,\dots,m_{\slots-1})$ and a set $I$, this function returns a ciphertext $\ct'$ that encrypts $\vm' = (m'_0,\dots,m'_{\slots-1})$ such that $m'_i = m_i$ if $i \in I$ and $m'_i = 0$ otherwise.

%\subsubsection{Special operations}\label{subsec:special_operations}

%One can also homomorphically permute the SIMD slots of a given ciphertext and act on them with the Frobenius automorphism.

%$\Rotate(\ct, i) \rightarrow \ct'$ with $i \in [0, \slots-1]$. Given a ciphertext $\ct$ encrypting SIMD slots
%$$\vm = (m_0,m_1,\dots,m_{\slots-1}),$$
%the rotation algorithm returns a ciphertext $\ct'$ that encrypts the cyclic shift of $\vm$ by $i$ positions, namely $(m_i,m_{(i+1) \mod \slots},\dots,m_{(i-1) \mod \slots})$.

%$\Frob(\ct, i) \rightarrow \ct'$ with $i\in[0,d-1]$. Given a ciphertext $\ct$ encrypting SIMD slots $\vm$ as above, the Frobenius algorithm returns a ciphertext $\ct'$ that encrypts a Frobenius map action on $\vm$, namely $(m^{p^i}_0,m^{p^i}_1,\dots,m^{p^i}_{\slots-1})$.

%As discussed in Section~\ref{subsec:funcff}, the $\Frob$ and $\Mul$ operations can be combined to compute the principal character $\princhar$, which turns non-zero values of SIMD slots into $1$ and leaves slots with zeros unchanged.

%$\IsNonZero(\ct) \rightarrow \ct'$. Given a ciphertext $\ct$ encrypting SIMD slots $\vm = (m_0,m_1,\dots,m_{\slots-1})$, this function returns a ciphertext $\ct'$ that encrypts:
%\[
%  (\princhar(m_0), \princhar(m_1), \dots, \princhar(m_{\slots-1})).
%\]
% Kim et al.~\cite{TDSC:KLLW16} showed that one can employ the Frobenius map to decrease the multiplicative depth of $\IsNonZero$.
%Recall that $\princhar(m) = m^{p^d-1} = \prod_{i=0}^{d-1} (m^{p-1})^{p^i}$ as shown in~(\ref{eq:exp_frob}).
%The multiplicative depth of $x^{p-1}$ is equal to $\ceil{\log_2 (p-1)}$.
%The multiplicative depth of $x^{p^i}$ is zero as it can be done by the $\Frob$ operation.
%In total, $d-1$ $\Frob$ operations are needed to compute $\princhar(m)$.
%As a result, the total multiplicative depth of $\IsNonZero$ is
%\begin{align}\label{eq:nonzero_depth}
%  \ceil{\log_2 (p-1)} + \ceil{\log_2 d}.
%\end{align}
%Using general exponentiation by squaring, $x^{p-1}$ requires $\floor{\log_2 (p-1)} + \wt(p-1) - 1$ field multiplications.
%Since $d-1$ field multiplications are needed to compute $\prod_{i=0}^{d-1} (x^{p-1})^{p^i}$, the total number of multiplications to compute $\princhar(m)$ is:
%\begin{align}\label{eq:nonzero_width}
%  \floor{\log_2 (p-1)} + \wt(p-1) + d - 2.
%\end{align}

Every homomorphic ciphertext contains a special component called \emph{noise} that is removed during decryption.
However, the decryption function can deal only with noise of small enough magnitude; otherwise, this function fails.
This noise bound is defined by encryption parameters in a way that larger parameters result in a larger bound.
The ciphertext noise increases after every homomorphic operation and, therefore, approaches its maximal possible bound.
It implies that to reduce encryption parameters one needs to avoid homomorphic operations that significantly increase the noise.
Therefore, while designing homomorphic circuits, we need to take into account not only the running time of homomorphic operations but also their effect on the noise.

%Table~\ref{table:he_operations} summarizes the running time and the noise cost of the aforementioned homomorphic operations.
%Similar to~\cite{C:HalSho14}, we divide the operations into expensive, moderate and cheap.
%The expensive operations dominate the cost of a homomorphic circuit.
%The moderate operations are less important, but if there are many of them in a circuit, their total cost can dominate the total cost.
%The cheap operations are the least important and can be omitted in the cost analysis.
The most expensive homomorphic operation with relation to both noise and running time is ciphertext-ciphertext multiplication ($\Mul$).
This operations takes place when two expressions containing input values are multiplied.
Such multiplication is called \emph{non-scalar}.
In contrast, ciphertext-plaintext multiplication ($\MulPlain$) is used when an expression with input values is multiplied by an unencrypted or publicly known value.
This is a \emph{scalar} multiplication.
Since $\Mul$ is much more expensive than $\MulPlain$, the multiplicative depth and complexity of a homomorphic circuit is usually calculated with relation to the number of $\Mul$'s, or non-scalar multiplications.
Thus, in the following sections we focus on the non-scalar complexity of comparison circuits.
%\begin{table}[t!]
%  \centering
%  \begin{tabular*}{6.5cm}{ p{2cm} p{2cm} p{2cm} }
%    \toprule
%    Operation	& Time			& Noise \\
%    \midrule
%    $\Add$		& cheap			& cheap 	\\
%    $\AddPlain$	& cheap			& cheap \\
%    $\Mul$		& expensive		& expensive 	\\
%    $\MulPlain$	& cheap			& moderate 	\\
%    $\Sub$		& cheap			& cheap  \\
%    $\SubPlain$	& cheap			& cheap  \\
%    $\Select$	& cheap			& moderate \\
%    $\Rotate$ 	 & expensive	& moderate \\
%    $\Frob$		 & expensive	& cheap \\
%    $\IsNonZero$ & expensive    & expensive \\
%    \bottomrule
%  \end{tabular*}
%  \caption{The cost of homomorphic operations with relation to running time and noise growth.}
%  \label{table:he_operations}
%\end{table}

% Let $\F_\fieldcard$ be a finite field of characteristic $\fieldchar$.
% We define the multiplicative map $\princhar_\fieldcard: \F_\fieldcard \rightarrow \{0,1\}, x \mapsto x^{\fieldcard-1} \mod \fieldchar$, which is called the \emph{principal character}.
% Due to Euler's theorem, $\princhar_\fieldcard(0) = 0$ and $\princhar_\fieldcard(x) = 1$ for any $x \in \F_\fieldcard^\times$.
% Since
% \begin{align}\label{eq:exp_frob}
% a^{t^d-1} = a^{(t-1)(t^{d-1} + \dots + 1)} = \prod_{i=0}^{d-1} (a^{t-1})^{t^i},
% \end{align}
% the principal character can be realized by Frobenius maps and multiplications.

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "main_pets"
%%% End:


\section{Schr\"odinger's Equation in Three Dimensions}
\subsection{TISE in 3D for Spherically Symmetric Potentials}
The TISE in 3D is in the form $\hat{H}X=EX$ where
$$\hat{H}=-\frac{\hbar^2}{2m}\nabla^2X+UX$$
In spherical coordiates $x=r\cos\phi\cos\theta,y=r\sin\phi\sin\theta,z=r\cos\theta$ where $r\in[0,\infty],\theta\in[0,\pi],\phi\in[0,2\pi)$, the Laplacian becomes
$$\nabla^2X=\frac{1}{r}\frac{\partial^2(rX)}{\partial r^2}+\frac{1}{r^2\sin^2\theta}\left( \sin\theta\frac{\partial}{\partial\theta}\left( \sin\theta\frac{\partial X}{\partial\theta} \right)+\frac{\partial^2X}{\partial\phi^2} \right)$$
We consider the case where $U=U(r,\theta,\phi)=U(r)$ and we are only looking for spherically symmetric solutions $X(r,\theta,\phi)=X(r)$.
Then the Hamiltonian becomes
$$\hat{H}X=-\frac{\hbar^2}{2m}\frac{1}{r}\frac{\mathrm d^2(rX)}{\mathrm dr^2}+UX=-\frac{\hbar^2}{2m}\left( \frac{\mathrm d^2X}{\mathrm dr^2}+\frac{2}{r}\frac{\mathrm dX}{\mathrm dr} \right)+UX$$
We have the normalisation condition
$$\int_{\mathbb R^3}|\psi^2|\,\mathrm dV<\infty\implies \int_0^\infty|X(r)|^2r^2\,\mathrm dr<\infty$$
which means $X(r)\to 0$ sufficiently fast as $r\to\infty$.\\
Consider $\sigma(r)=rX(r)$, then TISE becomes $\hat{H}\sigma=E\sigma$ on the half-plane $r\ge 0$.
Now the plan is to solve this on the whole line with $U(-r)=U(r)$.
As $X(0)$ are defined, $\sigma(0)=0$.
We only need to look for odd solutions $\sigma(-r)=-\sigma(r)$ since:
\begin{lemma}
    There is no nontrivial even solution to the problem.
\end{lemma}
\begin{proof}
    Suppose there is, say it is $\sigma_+$, then necessarily it is $C^2$ (for the equation to make sense) and hence $\sigma_+^\prime(0)=\sigma_+^{\prime\prime}(0)=0$.
    Then we have a corresponding odd solution
    $$\sigma_-(r)=\begin{cases}
        \sigma_+(r)\text{, for $r\ge 0$}\\
        -\sigma_+(r)\text{, for $r<0$}
    \end{cases}$$
    But then $\sigma(r)=\sigma_+(r)-\sigma_-(r)$ is a solution to the equation by linearity and vanishes for any $r>0$, which should not happen.
    \footnote{Well.}
\end{proof}
\begin{example}
    Consider the symmetric potential well
    $$U(r)=\begin{cases}
        0\text{, for $r\le a$}\\
        U_0\text{, for $r>a$}
    \end{cases}$$
    where $a,U_0>0$.
    For $0<E<U_0$, again let $k=\sqrt{2mE/\hbar^2}$ and $\bar{k}=\sqrt{2m(U_0-E)/\hbar^2}$, so
    $$\sigma(r)=\begin{cases}
        A\sin(kr)\text{, for $r\le a$}\\
        Be^{-\bar{k}r}\text{, for $r<a$}
    \end{cases}$$
    The boundary conditions gives $-k\cot(ka)=\bar{k}$ and we already know that $k^2+\bar{k}^2=2mU_0/\hbar^2$.
    Again define $\xi=ka,\eta=\bar{k}a$ and $r_0=a\sqrt{2mU_0/\hbar^2}$, so we have
    $$\begin{cases}
        -\xi\cot(\xi)=\eta\\
        \xi^2+\eta^2=r_0^2
    \end{cases}$$
    Now if $r_0<\pi/2$ (that is $U_0<\pi^2\hbar^2/(8ma^2)$), then there is no bounded solution.
    But unlike the one-dimensional case, we can always find at least one bounded state.
\end{example}
\subsection{The Radial Wavefunction of Hydrogen Atom}
The hydrogen atom consists of a proton $p^+$ and an electron $e^-$.
The Coulomb force is
$$F=-\frac{e^2}{4\pi\epsilon_0r^2}=-\frac{\partial U}{\partial r}\implies U(r)=-\frac{e^2}{4\pi\epsilon_0r}$$
So the bound states must have $E<0$, and $e^-$ is at rest $E=0$ as $r\to\infty$.
We want to look for stationary states of $e^-$ with spherically symmetric wavefunction $X=X(r)$ to
$$-\frac{\hbar^2}{2m}\left( \frac{\mathrm d^2X}{\mathrm dr^2}+\frac{2}{r}\frac{\mathrm dX}{\mathrm dr} \right)-\frac{e^2}{4\pi\epsilon_0r}X=EX$$
Then we need $E<0$ for bound states.
Define
$$\nu=\sqrt{-\frac{2mE}{\hbar^2}},\beta=\frac{e^2m}{2\pi\epsilon_0\hbar^2}$$
Then the equation becomes
$$\frac{\mathrm d^2X}{\mathrm dr^2}+\frac{2}{r}\frac{\mathrm dX}{\mathrm dr}+\left( \frac{\beta}{r}-\nu^2 \right)X=0$$
As $r\to\infty$, if we assume $X,X^\prime$ do not explode near $\infty$, then the equation becomes $X^{\prime\prime}-\nu^2X=0$, so $X(r)\sim e^{-\nu r}$ as $r\to\infty$.
This inspires us to try $X(r)=f(r)e^{-\nu r}$, which transforms the equation into
$$\frac{\mathrm d^2f}{\mathrm dr^2}+\frac{2}{r}(1-\nu r)\frac{\mathrm df}{\mathrm dr}+\frac{1}{r}(\beta-2\nu)f=0$$
which has a regular singular point at $r=0$, so we shall try the series solution $f(r)=r^c\sum_n a_nr^n$.
Plugging in,
$$0=\sum_{r=0}^\infty a_n(c+n)(c+n-1)r^{c+n-2}+\frac{2}{r}(1-\nu r)a_n(c+n)r^{c+n-1}+(\beta-2\nu)r^{c+n-1}$$
By looking at the coefficient of $r^{c-2}$, we have $0=a_0c(c+1)r^{c-2}$, so $c=-1$ or $c=0$.
The former is discarded as it has a singularity at $0$.
So $c=0$, hence $f(r)=\sum_na_nr^n$ and
$$0=\sum_{n=2}^\infty (a_nn(n+1)+a_{n-1}(\beta-2\nu))r^{n-2}=0\implies a_n=\frac{2\nu n-\beta}{n(n+1)}a_{n-1}$$
So all the coefficients are determined from $a_0$.
\begin{lemma}
    If the series above does not terminate, then the function $X(r)=f(r)e^{-\nu r}$ is not normalisable.
\end{lemma}
\begin{proof}
    If the series does not terminate then asymptotically $a_n\sim C(2\nu)^n/n!$ for some nonzero constant $C$ as $n\to\infty$.
    Therefore $f(r)\sim e^{2\nu r}$, hence $X(r)\sim e^{\nu r}$ as $r\to\infty$ which means that it is not normalisale.
\end{proof}
So necessarily there is some $N$ such that $2\nu N-\beta=0$, so $\nu=\beta/(2N)$.
We can work out the energy eigenfunction from that:
$$\nu^2=-\frac{2mE}{\hbar^2},\beta=\frac{e^2m}{2\pi\epsilon_0\hbar^2}\implies E=E_N=-\frac{e^4m}{32\pi^2\epsilon_0^2\hbar^2}\frac{1}{N^2}$$
which is exactly the energy levels deduced by Bohr's radius.
Would this mean that Bohr's model is fully correct?
Not really, as there can be solutions that are not spherically symmetric.\\
Let's find the eigenfunctions now.
Plugging the relation between $N,\nu$ and $\beta$ we have
$$\frac{a_n}{a_{n-1}}=-2\nu\frac{N-n}{n(n+1)}$$
$N=1$ gives a constant $f=f_1$, so $X_1(r)\propto e^{-\nu r}$.
$N=2$ gives $f_2(r)\propto 1-\nu r$, so $X_2(r)\propto (1-\nu r)e^{-\nu r}$.
$N=3$ gives $f_3(r)\propto 1-2\nu r+2\nu^2r^2/3$, so $X_3(r)=(1-2\nu r+2\nu^2r^2/3)e^{-\nu r}$.
And in general $f_N(r)=L_N(\nu r)$ where $L_N$ is the Legendre polynomial of order $N-1$ and hence $X_N(r)=L_N(\nu r)e^{-\nu r}$.
It is easy enough to normalise this for small $N$.
For the ground state $N=1$, the normalised wavefunction is
$$X_1(r)=\frac{\nu^{3/2}}{\sqrt{\pi}}e^{-2\nu r}=\frac{1}{\sqrt\pi}\left( \frac{e^2m}{4\pi \epsilon_0\hbar^2} \right)^{3/2}e^{-2\nu r}$$
With a little calculation we have $\langle r\rangle_{X_1}=3a_0/2$ where $a_0=2/\beta$ is the Bohr radius.
\subsection{Angular Momentum in Quantum Mechanics}
In classical dynamics, we defined the angular momentum $\underline{L}=\underline{x}\times\underline{p}$ which is a conserved quantity subject to spherically symmetrical potential.
Whereas in quantum mechanics, we have an analogous notion.
\begin{definition}
    The angular momentum operator is defined by $\underline{\hat{L}}=\underline{\hat{x}}\times\underline{\hat{p}}=-i\hbar\underline{x}\times\nabla$.
\end{definition}
Consequently components of $\underline{\hat{L}}$ are Hamiltonian and $[\hat{L}_i,\hat{L}_j]=i\hbar\epsilon_{ijk}\hat{L}_k\neq 0$ for $i\neq j$.
Therefore components of $\underline{\hat{L}}$ cannot be simultaneously measured.
\begin{definition}
    The total angular momentum operator is defined as $\hat{L}^2=|\hat{L}|^2=\hat{L}_1^2+\hat{L}_2^2+\hat{L}_3^2$.
\end{definition}
Then $[\hat{L}^2,\hat{L}_i]=0$ for all $i$ and $[\hat{H},\hat{L}^2]=0$ if $U$ is spherically symmetric.
To see the latter property, just observe that $[\hat{L}_i,\hat{x}_j]=i\hbar\epsilon_{ijk}\hat{x}_k$ and $[\hat{L}_i,\hat{p}_j]=i\hbar\epsilon_{ijk}\hat{p}_k$ and write $\hat{H}=\hat{p}^2/2m+\hat{U}$.
Consequently, fixing any $i$, $\{\hat{H},\hat{L}^2,\hat{L}_i\}$ is a set of $3$ mutually commuting operators.
Choose $i=3$, then $\hat{L}_3=\hat{L}_z$ is the $z$ component of angular momentum.
We can find simultaneous eigenstates of all three operators $\{\hat{H},\hat{L}^2,\hat{L}_3\}$.
The corresponding eigenvalues are observables.
Also, this set if maximal in the sense that there does not exists another independent operator other than $\hat{I}$ which commutes with all three.\\
What are the eigenfunctions?
We first try to find joint eigenfunctions of $\hat{L}^2,\hat{L}_3$.
In spherical polar coordinate, we can expand
$$\hat{L}^2=-\frac{\hbar^2}{\sin^2\theta}\left( \sin\theta\frac{\partial}{\partial\theta}\left( \sin\theta\frac{\partial}{\partial\theta} \right)+\frac{\partial^2}{\partial\phi^2} \right),\hat{L}_3=-i\hbar\frac{\partial}{\partial\phi}$$
If $Y=Y(\theta,\phi)$ is an eigenfunction of $\hat{L}_3$, then $\hat{L}_3Y=\hbar mY$ for some $m$.
Consequently $-iY_\phi=mY$.
Seperation of variables $Y(\theta,\phi)=y(\theta)x(\phi)$ gievs $x_\phi=imx$, so $x(\phi)=e^{im\phi}$.
But $x$ has to have period $2\pi$, so $m\in\mathbb Z$.
Now $\hat{L}^2(y(\theta)e^{im\phi})=\lambda y(\theta)e^{im\phi}$ gives
$$\frac{1}{\sin\theta}\frac{\partial}{\partial\theta}\left( \sin\theta\frac{\partial y}{\partial\theta} \right)-\frac{m^2}{\sin^2\theta}y(\theta)=-\frac{\lambda}{\hbar^2}y(\theta)$$
Which is Legendre equation.
By our study in Methods, we have
$$y_l(\theta)=P_{l,m}(\cos\theta)=(\sin\theta)^{|m|}\left.\frac{\mathrm d^{|m|}}{\mathrm dx^{|m|}}P_l(x)\right|_{x=\cos\theta}$$
where $P_l$ are the ordinary Legendre polynomials and $\lambda=l(l+1)\hbar^2$ for $-l\le m\le l$.
So the simultaneous eigenfunctions of $\hat{L}^2$ and $\hat{L}_3$ are labelled by $l=0,1,2,\ldots,m\in\{-l,\ldots,l\}$ and take the form
$$y_{l,m}(\theta,\phi)=P_{l,m}(\cos\theta)e^{im\phi}$$
with eigenvalues $m\hbar$ and $l(l+1)\hbar^2$ respectively.
Physically, we interpret $l$ as the total angular momentum numbers and $m$ the azimuthal quantum numbers.
Note that the constraint $m\in[-l,l]$ corresponds to the classical mechanical result of $-|L|\le L_3\le |L|$.\\
We can compute (whyyyyyyyy) some of these eigenfunctions (known as spherical harmonics):
$$Y_{0,0}=\frac{1}{\sqrt{4\pi}},Y_{1,0}=\sqrt{\frac{3}{4\pi}}\cos\theta,Y_{1,\pm 1}(\theta,\phi)=\mp\sqrt{\frac{3}{8\pi}}\sin\theta e^{\pm i\phi}$$
$$Y_{2,0}(\theta,\phi)=\sqrt{\frac{5}{16\pi}}(3\cos^2\theta-1),Y_{2,\pm 1}(\theta,\phi)=\mp\sqrt{\frac{15}{8\pi}}\sin\theta\cos\theta e^{\pm i\phi}$$
$$Y_{2,\pm 2}(\theta,\phi)=\sqrt{\frac{15}{32\pi}}\sin^2\theta e^{\pm 2i\phi}$$
\subsection{Full Wavefunction of the Hydrogen Atom}
Recall that in spherical polar,
$$\nabla^2X=\frac{1}{r}\frac{\partial^2(rX)}{\partial r^2}+\frac{1}{r^2\sin^2\theta}\left( \sin\theta\frac{\partial}{\partial\theta}\left( \sin\theta\frac{\partial X}{\partial\theta} \right)+\frac{\partial^2X}{\partial\phi^2} \right)$$
and
$$\hat{L}^2X=\frac{\hbar^2}{\sin^2\theta}\left( \sin\theta\frac{\partial}{\partial\theta}\left( \sin\theta\frac{\partial X}{\partial\theta} \right) +\frac{\partial^2}{\partial\phi^2}\right)$$
Therefore
$$-\hbar^2\nabla^2X=-\frac{\hbar^2}{r}\frac{\partial^2(rX)}{\partial r^2}+\frac{\hat{L}^2X}{r^2}$$
which means that we can rewrite the Hamiltonian as
$$\hat{H}X=-\frac{\hbar^2}{2m}\left( \frac{\partial^2X}{\partial r^2}+\frac{2}{r}\frac{\partial X}{\partial r} \right)+\frac{\hat{L}^2X}{2mr^2}-\frac{e^2}{4\pi\epsilon_0r}X$$
As $\{\hat{H},\hat{L}^2,\hat{L}_3\}$ is a set of commuting operators, we look for solutions to $\hat{H}X=EX$ of the form $X(r,\theta,\phi)=g(r)Y_{l,m}(\theta,\phi)$, which (after a lot of calculations) yields
$$\frac{\mathrm d^2g}{\mathrm dr^2}+\frac{2}{r}\frac{\mathrm dg}{\mathrm dr}-\frac{l(l+1)}{r^2}g+\frac{\beta}{r}g-\nu^2g=0,\nu=\sqrt{-\frac{2mE}{\hbar^2}},\beta=\frac{e^2m}{2\pi\epsilon_0\hbar^2}$$
The rest is similar to what we did for the spherically symmetrical case.
We seek solutions of the form $g(r)=f(r)e^{-\nu r}$ due to its limiting behavour, which gives
$$\frac{\mathrm d^2f}{\mathrm dr^2}+\frac{2}{r}(1-\nu r)\frac{\mathrm df}{\mathrm dr}-\frac{l(l+1)}{r^2}f+\frac{1}{r}(\beta-2\nu)f=0$$
The same procedure of finding series solution applies.
Since $0$ is a regular singular point, we try solutions of the form $f(r)=r^\sigma\sum_na_nr^n$.
By routine work of substituting we get the indicial equation $\sigma(\sigma-1)+2\sigma-l(l+1)=0$, hence $\sigma=l$ or $\sigma=-l-1$.
The latter case has to be discarded as we don't want singularity at $0$.
Therefore $f(r)=r^l\sum_na_nr^n$.
Again routine substitution work yields the recurrence
$$a_n=\frac{2\nu(n+l)-\beta}{n(n+2l+1)}a_{n-1}$$
which determines the series completely up to a constant.
The same trick as before applies:
If the series does not terminate, then by estimating the order of growth of $(a_n)$ we find that the $g$ that we want will not be normalisable.
Therefore the series must terminate.
This means that (for nonzero $a_0$) there exists some $n_{\max{}}$ such that $a_{n_{\max{}}}=0$ but $a_{n_{\max{}}-1}\neq0$ which has to satisfy
$$2\nu(n_{\max{}}+l)-\beta=0\implies \nu=\frac{\beta}{2N},N=n_{\max{}}+l$$
by plugging in the respective definition, the energy levels are
$$E=E_N=-\frac{e^4m}{32\pi^2\epsilon_0^2\hbar^2}\frac{1}{N^2}$$
So the spectrum of energy levels is identical to what we obtained in the special case where the eigenfunctions are spherically symmetric.
But in this more general setting, the eigenvalues can have some other (non-spherically-symmetric) eigenfunctions.
How many of them?
It's not hard to see:
For each $N$, there are exactly
$$D(N)=\sum_{l=0}^{N-1}\sum_{n=-l}^l1=\sum_{l=0}^{N-1}(2l+1)=N^2$$
many different eigenfunctions.
This is called the degeneracy of the energy value $E_N$.
So the full spectrum of the eigenfunctions of the Hydrogen atom is then
$$X_{N,l,m}(r,\theta,\phi)=\xi^lL_{N,l}(\xi)e^{-\xi}Y_{l,m}(\theta,\phi),\xi=\frac{\beta r}{2N}=\frac{e^2mr}{4N\pi\epsilon_0\hbar^2}$$
where $L_{N,l}$ (whose coefficients are defined by our terminating series earlier) are called the generalised Laguerre polynomials and $Y_{l,m}$ are the spherical harmonics.\\
$N=1,2,3,\ldots$ are called the principal quantum numbers, $l=0,\ldots,N-1$ are the total angular momentum quantum numbers and $m\in\{-l,\ldots,l\}$ are the azimuthal quantum numbers.
The Bohr model captured the case where $m=l\simeq N>>1$.
In this case $L_3==m\hbar\simeq N\hbar$ and $L=\sqrt{L^2}=\sqrt{l(l+1)\hbar^2}\simeq N\hbar$.\\
Note that due to the definition of the spherical harmonics, we have
$$\int_0^{2\pi}\int_{-1}^1\int_0^\infty |X_{N,l,m}(r,\theta,\phi)|^2r^2\,\mathrm dr\mathrm d(\cos\theta)\mathrm d\phi=\int_0^\infty |g(r)|^2r^2\,\mathrm dr$$
So we define $P(r)|g(r)|^2r^2$ as the radial probability.
Asymptotically,
$$P(r)=r^2|g(r)|^2\sim r^{2(l+1)}\exp\left( -\frac{\beta r}{2(l+1)} \right)$$
which, in the Bohr limit, just gives $r^{2N}\exp(-\beta r/N)$.
By differentiating, the stationary points of $P$ (i.e. the modes) are approximately at $r_{\rm peak}\simeq 2N^2/\beta=N^2r_1$ which is the same as what we obtained using Bohr's model.
\subsection{Towards Periodic Table}
If we have a nucleus with charge $+ze$ and there are $z$ electrons around it which are treated as independent particles (so ignore any interactions betweem electrons like electromagnetism and gravity), then the eigenfunction can be seperated as $X(\underline{x}_1,\ldots,\underline{x}_z)=X(\underline{x}_1)\cdots X(\underline{x}_z)$ where each $X(\underline{x}_i)$ is a rescaled solution for the Hydrogen atom.
Its energy level is then the sum of energies of all electrons $E=\sum_iE_i$.
which works for small $z$, but the interaction force between electrons is growing when $z$ is large -- which is why we need to develop more theory in next year's Principle of Quantum Mechanics.


\subsubsection{Critically Damped ($\Delta = 0$)}
This case isn't much more difficult.
The only difference is that because both roots $r_1$ and $r_2$ are $\frac{-b}{2m}$, we need an extra $t$ term in the solution. So, out solution is
\begin{equation*}
	y = C_1e^{r_1 t} + C_2te^{r_2 t}.
\end{equation*}
\begin{center}
	\includegraphics[width=0.5\textwidth]{./higherOrder/freeVibrs/criticallydamped.png}
\end{center}
Since both roots are once again negative,
\begin{equation*}
\lim\limits_{t \to 0}{C_1e^{r_1 t} + C_2te^{r_2 t}} = 0
\end{equation*}
meaning the mass's oscillation decays over time.


\documentclass[11pt, oneside]{article}

\usepackage{preamble}
\addbibresource{../../shared/references.bib}

\usepackage{sets}
\usepackage{topological-spaces}
\usepackage{groups}
\usepackage{real-numbers}

\usepackage{complex-numbers}

\title{Complex Numbers}
\author{Arthur Ryman, {\tt arthur.ryman@gmail.com}}
\date{\today}

\begin{document}

\maketitle

\begin{abstract}
This article contains Z Notation type declarations for the complex numbers, $\C$, and some related objects.
It has been type checked by \fuzz.
\end{abstract}

\section{Introduction}

The complex numbers, $\C$, are foundational to many mathematical objects such as vector spaces and manifolds,
but are not built-in to Z Notation.
This article provides type declarations for $\C$ and related objects so that they can be used and type checked in formal Z specifications.

No attempt has been made to provide complete, axiomatic definitions of all these objects since that would only be of use for proof checking.
Although proof checking is highly desirable, it is beyond the scope of this article.
The type declarations given here are intended to provide a basis for future axiomatization.

\section{Complex Numbers}

Z Notation does not predefine the set of complex numbers, so we define
them and operations on them here.

Although complex number operations are displayed using the same symbols as the
analogous real number operations,
they are distinct mathematical objects.
This distinction is apparent to the \fuzz\ type-checker and should not cause confusion to the human reader
because the underlying types of the objects will, as a rule, be clear from the context.
Visually distinct symbols will be used in cases where confusion is possible.

\subsection{$COMPLEX$}

A complex number can be thought of a pair of real numbers.
However, it is not correct to view any pair of real numbers as a complex number.
Therefore to denote a complex number we map a pair of real numbers
into the free type $COMPLEX$.

\begin{zed}
	COMPLEX ::= complex \ldata \R \cross \R \rdata
\end{zed}

Here the function $complex$ is a constructor that constructs a
complex number from a pair of real numbers.

\subsection{\zcmd{C}}

We introduce the usual notation $\C = COMPLEX$ for the set of complex numbers.

\begin{zed}
\C == COMPLEX
\end{zed}

\subsection{$Complex$}

Given real numbers $x$ and $y$, we can construct the complex number
$z = complex(x,y)$.
The real numbers $x$ and $y$ are referred to as the \textit{real} and \textit{imaginary} parts of $z$.
It's useful to introduce the schema $Complex$ that relates the complex number $z$ to its
real and imaginary parts $x$ and $y$.

\begin{schema}{Complex}
	z : \C \\
	x, y : \R
\where
	z = complex(x, y)
\end{schema}

\subsection{$real\_complex$}

Let $real\_complex(z)$ denote the real part $x$ of $z$.

\begin{zed}
	real\_complex == \{~ Complex @ z \mapsto x ~\}
\end{zed}

\subsection{\zcmd{realC}}

We introduce the usual notation $x = \realC(z)$ for the real part of $z$.

\begin{zed}
	\realC == real\_complex
\end{zed}

\subsection{$imag\_complex$}

Let $imag\_complex(z)$ denote the imaginary part $y$ of $z$.

\begin{zed}
	imag\_complex == \{~ Complex @ z \mapsto y ~\}
\end{zed}

\subsection{\zcmd{imagC}}

We introduce the usual notation $y = \imagC(z)$ for the imaginary part of $z$.

\begin{zed}
	\imagC == imag\_complex
\end{zed}

\subsection{$AddComplex$}

We can \textit{add} the complex numbers $z_1$ and $z_2$ to give their sum $z'$.
Let the schema $AddComplex$ denote this situation.

\begin{schema}{AddComplex}
	Complex_1 \\
	Complex_2 \\
	Complex'
\where
	x' = x_1 \addR x_2 \\
	y' = y_1 \addR y_2
\end{schema}

\subsection{$add\_complex$}

Let $add\_complex(z_1, z_2)$ denote the result of adding $z_1$ and $z_2$.

\begin{zed}
	add\_complex == \{~ AddComplex @ (z_1, z_2) \mapsto z' ~\}
\end{zed}

\subsection{\zcmd{addC}}

We introduce the usual notation $z' = z_1 \addC z_2$ for addition in $\C$.

\begin{zed}
	(\_ \addC \_) == add\_complex
\end{zed}

\subsection{$zero\_complex$}

Let $zero\_complex$ denote the \textit{zero} of $\C$.

\begin{zed}
	zero\_complex == complex (\zeroR, \zeroR)
\end{zed}

\subsection{\zcmd{zeroC}}

We introduce the usual notation $\zeroC \in \C$ for the zero of $\C$.

\begin{zed}
	\zeroC == zero\_complex
\end{zed}

\subsection{$NegComplex$}

We can \textit{negate} the complex number $z$ to give its negative $z'$.
Let the schema $NegComplex$ denote this situation.

\begin{schema}{NegComplex}
	Complex \\
	Complex'
\where
	x' = \negR x
\also
	y' = \negR y
\end{schema}

\subsection{$neg\_complex(z)$}

Let $neg\_complex(z)$ denote the negative of $z$.

\begin{zed}
	neg\_complex == \{~ NegComplex @ z \mapsto z' ~\}
\end{zed}

\subsection{\zcmd{negC}}

We introduce the usual notation $z' = \negC z$ for the negative of $z$.
\begin{zed}
	\negC == neg\_complex
\end{zed}

\subsection{The Additive Abelian Group $\C$}

\begin{theorem}

The complex numbers $\C$ form an Abelian group under addition.

\begin{zed}
(\_ \addC \_) \in \abgroup \C
\also
\zeroC = identity\_element(\_ \addC \_)
\also
\negC = inverse\_operation(\_ \addC \_)
\end{zed}

\end{theorem}

\subsection{$SubComplex$}

We can \textit{subtract} the complex number $z_1$ from $z_2$
to give their difference $z'$.
Let the schema $SubComplex$ denote this situation.

\begin{schema}{SubComplex}
	Complex_1 \\
	Complex_2 \\
	Complex'
\where
	x' = x_1 \subR x_2
\also
	y' = y_1 \subR y_2
\end{schema}

\subsection{$sub\_complex$}

Let $sub\_complex(z_1, z_2)$ denote the difference of $z_1$ and $z_2$.

\begin{zed}
	sub\_complex == \{~ SubComplex @ (z_1, z_2) \mapsto z' ~\}
\end{zed}

\subsection{\zcmd{subC}}

We introduce the usual notation $z' = z_1 \subC z_2$ for subtraction in $\C$.

\begin{zed}
	(\_ \subC \_) == sub\_complex
\end{zed}

\subsection{$nonzero\_complex$}

Let $nonzero\_complex$ denote the set of nonzero complex numbers.

\begin{zed}
	nonzero\_complex == \C \setminus \{ \zeroC \}
\end{zed}

\subsection{\zcmd{Cnz}}

We introduce the usual notation $\Cnz \subseteq \C$ to denote the set of nonzero complex numbers,
also referred to as the \textit{punctured complex number plane}.

\begin{zed}
	\Cnz == nonzero\_complex
\end{zed}

\subsection{$MulComplex$}

We can \textit{multiply} the complex numbers $z_1$ times $z_2$ to give their product $z'$.
Let the schema $MulComplex$ denote this situation.

\begin{schema}{MulComplex}
	Complex_1 \\
	Complex_2 \\
	Complex'
\where
	x' = x_1 \mulR x_2 \subR y_1 \mulR y_2
\also
	y' = x_1 \mulR y_2 \addR y_1 \mulR x_2
\end{schema}

\subsection{$mul\_complex$}

Let $mul\_complex(z_1, z_2)$ denote $z_1$ multiplied by $z_2$.

\begin{zed}
	mul\_complex == \{~ MulComplex @ (z_1, z_2) \mapsto z' ~\}
\end{zed}

\subsection{\zcmd{mulC}}

We introduce the usual notation $z' = z_1 \mulC z_2$ for multiplication in $\C$.

\begin{zed}
	(\_ \mulC \_) == mul\_complex
\end{zed}

\subsection{$MulNonzeroComplex$}

We can restrict multiplication in $\C$ to $\Cnz$.
Let the schema $MulNonzeroComplex$ denote this situation.

\begin{schema}{MulNonzeroComplex}
	MulComplex \\
\where
	z_1 \in \Cnz
\also
	z_2 \in \Cnz
\end{schema}

\subsection{$mul\_nonzero\_complex$}

Let $mul\_nonzero\_complex(z_1, z_2)$ denote the product of nonzero complex numbers.

\begin{zed}
	mul\_nonzero\_complex == \{~ MulNonzeroComplex @ (z_1, z_2) \mapsto z' ~\}
\end{zed}

\subsection{\zcmd{mulCnz}}

We introduce the usual notation $z' = z_1 \mulCnz z_2$ to denote the product.

\begin{zed}
	(\_ \mulCnz \_) == mul\_nonzero\_complex
\end{zed}

\subsection{$one\_complex$}

Let $one\_complex$ denote the multiplicative unit in $\C$.

\begin{zed}
	one\_complex == complex(\oneR, \zeroR)
\end{zed}

\subsection{\zcmd{oneC}}

We introduce the usual notation $\oneC \in \C$ for the unit of $\C$.

\begin{zed}
	\oneC == one\_complex
\end{zed}

\subsection{$InvNonzeroComplex$}

We can \textit{invert}
the nonzero complex number $z$ to get its inverse or reciprocal $z'$.
Let the schema $InvNonzeroComplex$ denote this situation.

\begin{schema}{InvNonzeroComplex}
	z, z' : \Cnz
\where
	z \mulCnz z' = \oneC
\end{schema}

\subsection{$inv\_nonzero\_complex$}

Let $z' = inv\_nonzero\_complex(z)$ denote the inverse of $z$.

\begin{zed}
	inv\_nonzero\_complex == \{~ InvNonzeroComplex @ z \mapsto z' ~\}
\end{zed}

\subsection{\zcmd{invCnz}}

We introduce the usual notation $z' = z \invCnz$ for the inverse.

\begin{zed}
	(\_ \invCnz) == inv\_nonzero\_complex
\end{zed}

\subsection{$DivNonzeroComplex$}

We can \textit{divide} the nonzero complex numbers $z_1$ by $z_2$ to get their quotient $z'$.
Let the schema $DivNonzeroComplex$ denote this situation.

\begin{schema}{DivNonzeroComplex}
	z_1, z_2, z' : \Cnz
\where
	z_1 = z' \mulCnz z_2
\end{schema}

\subsection{$div\_nonzero\_complex$}

Let $z' = div\_nonzero\_complex(z_1, z_2)$ denote $z_1$ divided by $z_2$.

\begin{zed}
	div\_nonzero\_complex == \{~ DivNonzeroComplex @ (z_1, z_2) \mapsto z' ~\}
\end{zed}

\subsection{\zcmd{divCnz}}

We introduce the usual notation $z_1 \divCnz z_2$ to denote division.

\begin{zed}
	(\_ \divCnz \_) == div\_nonzero\_complex
\end{zed}

\subsection{The Multiplicative Abelian Group $\Cnz$}

\begin{theorem}
The nonzero complex numbers $\Cnz$ form an Abelian group under multiplication.

\begin{zed}
(\_ \mulCnz \_) \in \abgroup \Cnz
\also
\oneC = identity\_element(\_ \mulCnz \_)
\also
(\_ \invCnz) = inverse\_operation(\_ \mulCnz \_)
\end{zed}

\end{theorem}

\subsection{$NormComplex$}

The $norm$ of a complex number $z$ is a non-negative real number $r$
equal to the Euclidean length of its underlying pair of real numbers regarded
as a vector in the Euclidean plane.
Let the schema $NormComplex$ denote this situation.

\begin{schema}{NormComplex}
	Complex \\
	r : \R
\where
	r = \sqrtR(x \mulR x \addR y \mulR y)
\end{schema}

\subsection{$norm\_complex$}

Let $r = norm\_complex(z)$ be the norm of $z$.

\begin{zed}
	norm\_complex == \{~ NormComplex @ z \mapsto r ~\}
\end{zed}

\subsection{\zcmd{normC}}

We introduce the usual notation $r = \normC(z)$ to denote the norm of $z$.

\begin{zed}
	\normC == norm\_complex
\end{zed}

\printbibliography

\end{document}


\chapter{Metrics}

A metric is a function that measures the distance between two points.

Let \(S\) be a space.

Let \(d : S \to S \to \Real\) be a metric of \(S\).

Thus \(d(x,y)\) is the distance from \(x\) to \(y\).

Thus \(d\) should satisfy \(d(x,y) = d(y,x)\).

\section*{Euclidean metrics of real tuple spaces}

Let \(d : \Real^n \to \Real^n \to \Real\).
Define \(d(x,y) = \sqrt{\sum_{k=1}^n (x_k - y_k)^2}\).
Then \(d\) we say that \(d\) an Euclidean metric of \(\Real^n\).

\section{Norms and metrics induce each other}

A norm induces a metric.
A metric induces a norm.%
\footnote{\url{https://en.wikipedia.org/wiki/Metric_(mathematics)\#Metrics_on_vector_spaces}}

\section{Geodesics}

The distance between two points is the length of the shortest curve that connects them.

\section{Measuring distances on curved spaces}

Example: circle

Draw a circle with center \(C\).
Draw two points \(P\) and \(Q\) on the circle's perimeter.
Then \(CPQ\) forms a sector whose arc is \(PQ\).
The distance from \(P\) to \(Q\) is that arc's length.

Every point the circle can be described by a real number \(a\).
This real number is the \enquote{angle} of the point.

\(d(a,b) = r \cdot (b-a)\).

TODO define a metric for a curve described by \(x : \Real \to \Real^2\).

A curve is in length-normal formulation (???)
iff \( L(t,u) = \abs{t-u} \).
Then the metric is \(d(x,y) = L(f^{-1}(x), f^{-1}(y))\).

We can also define.
\(d(a,b) = b-a\).

\footnote{\url{https://en.wikipedia.org/wiki/Intrinsic_metric}}

Draw a sphere with center \(C\).
Draw two points \(P\) and \(Q\) on the sphere.

\section{Generalizing shortest paths into geodesics}

\subsection{Understanding the shortest curve connecting two points}

The concept of geodesic arises naturally when we realize
that \emph{straightness} is defined in terms of \emph{distance}.
If we define a \emph{straight} line segment as the \emph{shortest path} connecting its endpoints,
then the concept of geodesics arises naturally by redefining what \emph{shortest} means.

In Euclidean geometry, the shortest path connecting two points is a line segment.
Remember that a line is a straight curve.

We can also write \emph{shortest} as \emph{having minimum distance},
to clarify the connection between straightness and distance.

A curve segment connecting two points is a \emph{geodesic}
iff the length of the curve segment is the distance between the two points.

If \(x\) is a point on a geodesic,
then every point \(x + h\) satisfying \(\norm{h} = d(x,x+h)\) is also on the geodesic.
Can this equation be used to derive the equation of a geodesic?
The definitions of the norm \(\norm{\cdot}\) and the distance \(d\) depend on the ambient space.

Thus geodesic is a generalization of straightness.
By \emph{straight}, we mean \emph{shortest} (having minimal length).
Every line is a geodesic.

A geodesic is a locally length-minimizing curve.%
\footnote{\url{http://mathworld.wolfram.com/Geodesic.html}}

In metric geometry, a geodesic is a curve which is everywhere locally a distance minimizer.%
\footnote{\url{https://en.wikipedia.org/wiki/Geodesic\#Metric_geometry}}

\subsection{Finding the equation of a geodesic}

If the curve is given by parametric equation,
then a geodesic equation can be obtained by minimizing the arc length of the curve?%
\footnote{\url{http://mathworld.wolfram.com/Geodesic.html}}

\section{Metric tensor}

We have always implicitly assumed that a space defines distance uniformly,
the same everywhere, that is, we have always assumed the isometry \(d(x+h,y+h) = d(x,y)\) for all \(h\).

\footnote{\url{https://en.wikipedia.org/wiki/Metric_tensor}}%
\footnote{\url{https://en.wikipedia.org/wiki/Arc_length\#Generalization_to_.28pseudo-.29Riemannian_manifolds}}

A metric tensor is a metric in tensor form?
A rank-\((a,b)\) tensor is a function with \(a+b\) parameters?

Dot product generalizes to inner product.

Typing rule:
if \( a, b : V \), then \( \langle a, b \rangle : \Real \).
An inner product is a function with type \( V \to V \to \Real \).

In Euclidean vector spaces,
\( \langle x, y \rangle = x \cdot y \).
The dot product is the inner product of Euclidean vector spaces.

An inner product defines orthogonality. Two vectors are orthogonal iff \( \langle x, y \rangle = 0 \).
An inner product also defines the length of a vector.
\[
\norm{x} = \sqrt{\langle x, x \rangle}
\]

Tissot's indicatrices visualize a metric tensor by scattering
many circles throughout a space
so that we can see how the space's metric tensor distorts them.
This method tells us how much our map is lying to us.%
\footnote{\url{https://en.wikipedia.org/wiki/Tissot\%27s_indicatrix}}
\disabled{}%vim indent bug

\( d(0,x) = \norm{x} \) only in Euclidean geometry?

Perhaps we should digress to mapmaking/cartography?

Motivate metric tensor using cartography?
The surface of the Earth is a sphere.
How do we project its surface to a flat paper?
How do we draw a map?

Inner product generalizes to metric tensor?

A metric tensor's type is also \( V \to V \to \Real \).

Metric on half circle \( \{ (r \cos t, r \sin t) ~|~ t \in [0,\pi] \} \).

\section{Wrong-but-useful is better than right-but-useless}

Ancient people believe that the Earth is a plate.

Most people in 2017 believe that the Earth is a ball.

The Earth is an oblate spheroid.
It's a slightly flattened sphere.
It's wider on the equator.

The Earth is irregular.

Note how the statements become more correct, less general, and less applicable.

Earth is a plate, ball, or spheroid, depending on what we are doing.
If we're driving a car, the Earth is a plate.
If we're trying to introduce differential geometry by analogy with the Earth, it's a ball.
If we are comparing the gravitational pull in many places,
then the Earth is a spheroid.
If we are trying to one-up someone else, then the Earth is irregular;
it has mountains and lakes.

We're abusing language.
What do we mean by \enquote{is}?

Wrong-but-useful is better than right-but-useless.


\chapter*{Appendix I}
\addcontentsline{toc}{chapter}{Appendix I}
\label{chapter:appendix1}

\textbf{Ulceration risk of pressure-time relation}

Based on pressure-time cell death experiment, this equation shows the higher threshold of constant pressure at a certain time T
\begin{equation}
    P(T) = \frac{P_{max}-P_{min}}{1 + e^{\lambda(T-T_0)}} + P_{min}
\end{equation}

Here,

\begin{align*}
    P_{max} &= 31 kPa\\
    P_{min} &= 8 kPa\\
    \lambda &= 0.15 min^{-1}\\
    T_0     &= 95 min
\end{align*}

(These values are based on experiment expect for $T_0$ which is arbitrary)

Following equation shows the maximum safe time ($T_{max}$) for particular pressure value.
\begin{equation}
    T_{max}(P) =
    \begin{cases}
        \infty & P < P_{min}\\
        0  & P > P_{max}\\
        T_0 + \frac{1}{\lambda}\left( \frac{P_{max}-P_{min}}{P-P_{min}} - 1 \right) & P_{min} < P < P_{max}
    \end{cases}
\end{equation}

The risk of the particular pressure value is given by this equation
\begin{equation}
    \delta R = \frac{\delta t}{T_{max}(P)}
\end{equation}

Cumulative risk is calculated in the following way.

\begin{enumerate}
    \item Sum risk when pressure is greater than $P_{min}$.
    \item Set total risk to zero when pressure becomes lesser than $P_{min}$.
\end{enumerate}

According to this risk metric it is shown that supine posture has higher risk. It further shows that the supine will generate same risk as left or right postures with half of period.

\chapter*{Appendix II}
\addcontentsline{toc}{chapter}{Appendix II}
\label{chapter:appendix2}

Schematic of the pressure mat
\input{figs/schematic1.tex}

% \textbf{Mean Field Algorithm} \\
% \input{figs/algo.tex}

% \chapter*{Appendix III}
% \addcontentsline{toc}{chapter}{Appendix III}
% \label{chapter:appendix3}

% ATMega code


\subsubsection{Complex Roots}
\noindent
Although the previous two theorems already cover complex roots, we can simplify solutions that have complex roots into functions we more easily understand.\\

\begin{theorem}
	If an auxiliary equation has roots $\alpha \pm \beta i$, then $C_1e^{\alpha x}\cos{(\beta x)}$ and  $C_2e^{\alpha x}\sin{(\beta x)}$ are fundamental solutions.
\end{theorem}
\begin{proof}
	The two corresponding fundamental solutions are
	\begin{equation*}
		C_1e^{(\alpha + \beta i)x} \text{, } C_2e^{(\alpha - \beta i)x}
	\end{equation*}
	so the part of the general solution for these two fundamental solutions are
	\begin{equation*}
		C_1e^{(\alpha + \beta i)x} + C_2e^{(\alpha - \beta i)x}.
	\end{equation*}
	Using Euler's formula, we can also write this as
	\begin{equation*}
		C_1 e^{\alpha x}\left( \cos{(\beta t)} + i\sin{(\beta x)} \right) + C_2e^{\alpha x}\left( \cos{(-\beta x)} + i\sin{(-\beta x)} \right).
	\end{equation*}
	Using the fact that $\sin{(-x)} = -\sin{x}$, $\cos{(-x)} = -\cos{x}$ and separating into real and imaginary parts,
	\begin{equation*}
		 = \left[ C_1e^{\alpha x}\cos{(\beta x)} + C_2e^{\alpha x}\cos{(\beta x)} \right] + i\left[ C_1e^{\alpha x}\sin{(\beta x)} - C_2e^{\alpha x}\sin{(\beta x)} \right].
	\end{equation*}
	Simplifying \footnote{\label{note1}In this step the values of $C_1$ and $C_2$ might have changed, but they are still constants.},
	\begin{equation*}
		= e^{\alpha x}\left(C_1\cos{(\beta x)} + iC_2\sin{(\beta x)}\right).
	\end{equation*}
	At this point, we need to consider if the constants are real or imaginary.
	We would then take the real part as a fundamental solution.\\
	If they are both real, then a fundamental solution is\footnote{See footnote \ref{note1}}
	\begin{equation*}
		C_1e^{\alpha x}\cos{(\beta x)}
	\end{equation*}
	where $C_1$ is a real constant.
	If they are both imaginary, the a fundamental solution is\footnote{See footnote \ref{note1}}
	\begin{equation*}
		C_2e^{\alpha x}\sin{(\beta x)}
	\end{equation*}
	where $C_2$ is a real constant.
\end{proof}

\noindent
If complex roots are repeated, we just add the appropriate number of powers of $x$ in front of both the $\sin{(\beta x)}$ and $\cos{(\alpha a)}$ parts.
\pagebreak % It looked weird having the example start and then the footnote immediately after, so now the example starts on the next page

\begin{example}
	Find the general solution to the following differential equation.
	\begin{equation*}
		y^{(4)} + 2y^{\prime\prime} + y = 0
	\end{equation*}
\end{example}
\noindent
First we extract the auxiliary equation and find its roots.
\begin{equation*}
	r^4 + 2r^2 + 1 = 0 \implies r = i (\text{double root}), -i (\text{double root}).
\end{equation*}
Since we have complex roots $0 \pm 1i$, we know that the following are fundamental solutions
\begin{equation*}
	C_1e^{0x}\cos{1x} \to C_1\cos{x} \text{ and } C_2e^{0x}\sin{1x} \to C_2\sin{x}.
\end{equation*}
Since both roots are double roots the following are also fundamental solutions:
\begin{equation*}
	C_3x\cos{x} \text{ and } C_4x\sin{x}.
\end{equation*}
So, the general solution is
\begin{equation*}
	y = C_1\cos{x} + C_2\sin{x} + C_3x\cos{x} + C_4x\sin{x}.
\end{equation*}


%!TEX root = ../gfkg.tex
\subsection{Chapter 1}
\begin{p}
{Let $\vec{k}\in\R^3$ and lt $\omega=|\vec{k}|$. Fix $\vec{E}\in\mathbb{C}^3$ with
$\vec{k}\cdot\vec{E}=0$ and $\vec{k}\times\vec{E}=i\omega\vec{E}$. Show that
$\vec{\mathcal{E}}(t,\vec{x})=\vec{E}e^{-i(\omega t-\vec{k}\cdot\vec{x})}$ satisfies the
vacuum Maxwell equations.}
\end{p}
{...}