% Copyright 2018 Melvin Eloy Irizarry-Gelpí
\chapter{Simple Harmonic Motion}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Preliminary}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
When an elastic spring is stretched or compressed beyond its natural relaxed length, a restorative force arises on the spring that causes the spring to return to its natural relaxed length. This force is proportional to how much distance $x$ the spring is stretched:
\begin{equation} \label{eq.11.hooke}
    F_{k} = - k x
\end{equation}
Here the minus sign is due to the restorative nature of the force (it is always opposite to what the spring is doing), and $k$ is the spring constant.

If a mass $m$ is attached to one end of the spring, the mass will move back-and-forth when the spring is stretched or compressed. Due to Newton's second law, you have a relation between force and acceleration:
\begin{equation}
    F_{\text{net}} = m a \quad \Longrightarrow \quad -kx = m a
\end{equation}
Or in other words:
\begin{equation} \label{eq.11.ax}
    a = -\left( \frac{k}{m} \right) x
\end{equation}
That is, for this motion, the acceleration is proportional to the amount of distance that the spring is stretched or compressed. Note that the slope is negative.

When you look at the position as it change with time, it follows a pattern similar to a sine or cosine function, familiar from trigonometry. This suggest a sinusoidal fit for position $x$ as a function of time $t$:
\begin{equation}
    x(t) = A \sin{\left( Bt + C \right)} + D
\end{equation}
Here $A$ is the amplitude of the motion (in m), $B$ is the angular frequency (in rad/s), $C$ is the time shift (in rad), and $D$ is the position shift (in m). Velocity is defined as the rate of change of position with respect to time. With calculus, this is equivalent to taking a derivative with respect to time:
\begin{equation} \label{eq.11.v}
    v(t) = \frac{\mathrm{d} x}{\mathrm{d} t} = AB \cos{\left( Bt + C \right)}
\end{equation}
That is, the parameters that describe the fit for position ($A$, $B$, $C$, and $D$) can also be used to describe the fit for velocity. Similarly, acceleration is defined as the rate of change of velocity with respect to time. With calculus, this is equivalent to taking a derivative with respect to time:
\begin{equation} \label{eq.11.a}
    a(t) = \frac{\mathrm{d} v}{\mathrm{d} t} = -AB^{2} \sin{\left( Bt + C \right)}
\end{equation}
Again, the parameters that describe the fit for position can also be used to describe the fit for acceleration.

For a mass $m$ attached to a spring with spring constant $k$, the period of oscillation is given by
\begin{equation}
    T = 2\pi \sqrt{\frac{m}{k}}
\end{equation}
The period is the time it takes for the mass to do one full cycle. Related to the period is the angular frequency $\omega$:
\begin{equation} \label{eq.11.omega}
    \omega = \frac{2 \pi}{T} = \sqrt{\frac{k}{m}}
\end{equation}
As you are going to see, the same value of angular frequency controls how quickly position, velocity, acceleration, and force change with time.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Experiment}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
We are going to use a motion sensor to measure the position, velocity and acceleration of a mass hanging from a spring. The spring in turn hangs from a force sensor that we are going to use to measure force. When the sensor is zeroed correctly, the constant weight force $mg$ is taken into account. When the hanging mass is moved from equilibrium and released, the motion is oscillatory.

After recording data for a short time, you can use the LabQuest device to obtain the values of the parameters $A$, $B$, $C$, and $D$ that best describe the force and the position data versus time.

We are going to do four combinations of mass and spring constant, as stated in Table \ref{table.11.parameters}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{table}
    \centering
    \begin{tabular}{|r|r|r|}\hline
        $k$ (N/m) & $m$ (kg) & $\omega$ (rad/s) \\ \hline
        5 & 0.05 & 10 \\
        5 & 0.1 & 7.071 \\
        15 & 0.1 & 12.247 \\
        15 & 0.15 & 10 \\
        \hline
    \end{tabular}
    \caption{Four combinations of mass and spring constant, along with $\omega$ prediction}
    \label{table.11.parameters}
\end{table}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Analysis}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
There are many aspects of simple harmonic motion that can be verified with this experiment.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Force and Position}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
You can verify Hooke's law, equation (\ref{eq.11.hooke}), by making a scatter plot chart with position in the horizontal axis, and force in the vertical axis. The shape of this graph is a downward line, as in Figure \ref{figure.11.hooke}. You can find the slope with the \texttt{SLOPE} function. If position is in column X with the first value in row 6, and force is in column Y, with first value in row 6; then the command is
\begin{center}
    \texttt{=SLOPE(Y6:Y, X6:X)}
\end{center}
The linear behavior confirms Hooke's law. The slope of the linear fit corresponds to the (negative) value of the spring constant. Conversely, the negative of the slope serves as an indirect measurement of the spring constant:
\begin{equation}
    k_{\text{exp}} = - (\text{slope of force versus position linear fit})
\end{equation}
Note that position and force data come from different sensors.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{figure}
    \centering
    \includegraphics[scale=0.71]{image/11-shm/hooke.png}
    \caption{}
    \label{figure.11.hooke}
\end{figure}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Force and Acceleration}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
You can verify Newton's second law of motion by making a scatter plot chart with acceleration in the horizontal axis, and force in the vertical axis. The shape of this graph is an upward line, as in Figure \ref{figure.11.newton}. You can find the slope with the \texttt{SLOPE} function. The linear behavior confirms Newton's second law, and the value of the slope is mass. You can use this slope as an indirect measurement of the amount of mass hanging from the spring:
\begin{equation}
    m_{\text{exp}} = \text{slope of force versus acceleration linear fit}
\end{equation}
Note that acceleration and force data come from different sensors.

Together with the measurement of the spring constant from the force versus position graph, you can compute an experimental estimate of the angular frequency via
\begin{equation}
    \omega_{1} = \sqrt{\frac{k_{\text{exp}}}{m_{\text{exp}}}}
\end{equation}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{figure}
    \centering
    \includegraphics[scale=0.71]{image/11-shm/newton.png}
    \caption{}
    \label{figure.11.newton}
\end{figure}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Acceleration and Position}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Combining Hooke's law with Newton's second law of motion gives equation (\ref{eq.11.ax}). Using the definition of $\omega$ in equation (\ref{eq.11.omega}), we find that indeed,
\begin{equation}
    a = -\omega^{2}x
\end{equation}
That is, for simple harmonic motion, the acceleration is proportional to the position with the slope being the (negative) squared angular frequency. The shape of this graph is a downward line, as in Figure \ref{figure.11.ax}. The slope of this graph is the negative of the squared angular frequency. This value provides another experimental estimate of the angular frequency:
\begin{equation}
    \omega_{2} = \sqrt{- (\text{slope of acceleration versus position})}
\end{equation}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{figure}
    \centering
    \includegraphics[scale=0.71]{image/11-shm/a-vs-x.png}
    \caption{}
    \label{figure.11.ax}
\end{figure}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Common Angular Frequency}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
From the LabQuest device, you can obtain the parameters for the sinusoidal fit for position and force. The values for $A$, $C$, and $D$ will not necessarily agree, but the values for $B$ in both fits should be very close. Indeed, the $B$ from the force and position fits provide yet more experimental estimates of the angular frequency:
\begin{equation}
    \omega_{3} = B \text{ from force fit}
\end{equation}
and
\begin{equation}
    \omega_{4} = B \text{ from position fit}
\end{equation}
Note that, since the data for position and force comes from different sensors, these measurements can be taken as fully independent.

In principle you can perform a sinusoidal fit on velocity and acceleration too. However, the parameters of these fits are not independent. Indeed, theoretically, they depend on the parameters for the position fit as stated in equations (\ref{eq.11.v}) and (\ref{eq.11.a}). In class we saw how you can use compute the fit functions in (\ref{eq.11.v}) and (\ref{eq.11.a}) with the parameters from the position fit, and how those function are in very good agreement with the experimental data collected.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Velocity and Position}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
A graph with velocity and position is called a phase space graph. For this particular experiment with simple harmonic motion, the velocity and position data yield an elliptical shape (a closed orbit), as in Figure \ref{figure.11.phase}. Now you know!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{figure}
    \centering
    \includegraphics[scale=0.71]{image/11-shm/phase.png}
    \caption{}
    \label{figure.11.phase}
\end{figure}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{My Data}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The results for my run 1 are summarized in Table \ref{table.11.results}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{table}
    \centering
    \begin{tabular}{|l|r|}
        \hline
        Name & Value \\
        \hline
        $m_{\text{exp}}$ & 0.0498 kg \\
        $k_{\text{exp}}$ & 4.4255 N/m \\
        $\omega_{1}$ & 9.4230 rad/s \\
        $\omega_{2}$ & 9.3776 rad/s \\
        $\omega_{3}$ & 9.5802 rad/s \\
        $\omega_{4}$ & 9.5796 rad/s \\
        \hline
        $\omega_{\text{ave}}$ & 9.4901 rad/s \\
        \hline
    \end{tabular}
    \caption{Results for run 1. The last row is the average of the previous four rows.}
    \label{table.11.results}
\end{table}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Your Data}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Your Lab Report}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
In your lab report you should include:
\begin{enumerate}
    \item A version of Table \ref{table.11.results} with four runs, one for each different mass/spring constant combination. You do not have to make the graphs in order to get the slopes; use the \texttt{SLOPE} function.
    \item One acceleration versus position graph with the linear fit, for a run of your choosing.
    \item One force versus acceleration graph with the linear fit, for a run of your choosing.
    \item One force versus position graph with the linear fit, for a run of your choosing.
    \item One velocity versus position graph for a run of your choosing.
\end{enumerate}
You should answer the following questions:
\begin{enumerate}
    \item Based on your analysis and what we saw in class, are you convinced that (for simple harmonic motion) all of position, velocity, acceleration, and force can be described by sines or cosines with a common angular frequency?
    \item Is the angular frequency parameter $B$ for the position versus time graph the same or close to the angular frequency parameter $B$ for the force versus time graph?
    \item Can you test Newton's second law with the data from this experiment? Does the measured mass agree with the expected value used?
    \item Can you test Hooke's law with the data from this experiment? Does the measured spring constant agree with the expected value used?
    \item Are your four estimates of the angular frequencies close to the expected theoretical value given by (\ref{eq.11.omega}).
\end{enumerate}


\subsection{Velocity Field for a Rigid Body}

\begin{frame}{Introduction}
\begin{figure}[ht]
	\includegraphics[width=80mm]{images/v_a.png}
\end{figure}
	Let $M$ be a point in rigid body $(R_1)$. Then $\vb{r}{M}$ is the position vector of $M$ relative to fixed reference frame $(O_0x_0y_0z_0)$.
	\[
	\vb{r}{M} = \vb{r}{O} + \vb{r}{MO} = \vb{r}{O} + x\ih+y\jh+z\kh
	\]
\end{frame}

\begin{frame}
	For Cartesian coordinates, the following relations are true:
	\[\begin{cases}
		\ih\cdot\ih=\jh\cdot\jh=\kh\cdot\kh=1\\
		\ih\cdot\jh=\jh\cdot\kh=\kh\cdot\ih=0
	\end{cases}\]

	Velocity vector $\vb{v}{M}=\xvec[.]{\bm{r}}_{\bm{M}}$ with respect to time $t$:
	\[
	\vb{v}{M} = \vb{v}{O} + \dot{x}\ih + \dot{y}\jh + \dot{z}\kh + x\frac{d\ih}{dt} + y\frac{d\jh}{dt} + z\frac{d\kh}{dt}
	\]

	For a rigid body, $\dot{x}=\dot{y}=\dot{z}=0$
	\[
	\Rightarrow\vb{v}{M}=\vb{v}{O}+x\frac{d\ih}{dt}+y\frac{d\jh}{dt}+z\frac{d\kh}{dt}
	\]
\end{frame}

\begin{frame}
	Let $\vb{\omega}{} = \omega_x\ih + \omega_y\jh + \omega_z\kh$ be rotational vector of rigid body $(R_1)$. Then
	\[
	\vb{\omega}{} = (\frac{d\ih}{dt}\cdot\jh)\ih+ (\frac{d\jh}{dt}\cdot\kh)\jh + (\frac{d\kh}{dt}\cdot\ih)\kh\]\[\hskip 13mm=(-\ih\cdot\frac{d\jh}{dt})\ih+(-\jh\cdot\frac{d\kh}{dt})\jh+(-\kh\cdot\frac{d\ih}{dt})\kh
	\]
	Combine with the fact that $\displaystyle \frac{d\ih}{dt}\cdot\ih=\frac{d\jh}{dt}\cdot\jh=\frac{d\kh}{dt}\cdot\kh=0$\vskip1.25mm
	$\displaystyle \frac{d\ih}{dt}=(\frac{d\ih}{dt}\cdot\ih)\ih + (\frac{d\ih}{dt}\cdot\jh)\jh + (\frac{d\ih}{dt}\cdot\kh)\kh= 0\ih+\omega_z\jh-\omega_y\kh=\vb{\omega}\times\ih$\\
	$\displaystyle \frac{d\jh}{dt}=(\frac{d\jh}{dt}\cdot\ih)\ih + (\frac{d\jh}{dt}\cdot\jh)\jh + (\frac{d\jh}{dt}\cdot\kh)\kh=-\omega_z\ih+0\jh+\omega_x\kh=\vb{\omega}\times\jh$\\
	$\displaystyle \frac{d\kh}{dt}=(\frac{d\kh}{dt}\cdot\ih)\ih + (\frac{d\kh}{dt}\cdot\jh)\jh + (\frac{d\kh}{dt}\cdot\kh)\kh= \omega_y\ih-\omega_x\jh+0\kh=\vb{\omega}\times\kh$
	\[
	\Rightarrow\vb{v}{}=\vb{v}{O}+\vb{\omega}{}\times(x\ih+y\jh+z\kh)
	\]
\end{frame}

\begin{frame}
	\begin{block}{Formula}
		For any point of a rigid body, its velocity equation is:
		\[
		\vb{v}{} = \vb{v}{O} + \vb{\omega}{}\times\vb{r}{}
		\]
		where $\vb{\omega}{}\times \vb{r}{}$ is the rotational motion of that point with respect to $O$

	\end{block}
	\emph{Example}\vskip 2.5mm
	In matrix form, velocity vector $\vb{v}{M}$ of point $M$ relative to fixed reference frame $(O_0x_0y_0z_0)$ can be written as:
	\[
	\vb{v}{M}=
	\begin{bmatrix}
	v_x\\v_y\\v_z
	\end{bmatrix}=
	\begin{bmatrix}
	v_{Ox}+z\omega_y-y\omega_z\\v_{Oy}+x\omega_z-z\omega_x\\v_{Oz}+y\omega_x-x\omega_y
	\end{bmatrix}=
	\vb{v}{O}+\vb{\omega}{}\times\vb{r}{MO}
	\]
\end{frame}


\subsection{Modelling vaccine effects}
We stratified all model compartments as either vaccinated or unvaccinated and commenced simulations with an fully unvaccinated population. With vaccination roll-out, individuals in the susceptible and recovered compartments move from “unvaccinated” to “vaccinated” at a constant rate representing vaccine administration over time. The daily rate of vaccination is calculated from the vaccine coverage achieved over a given period of time is calculated as $rate_{vac} = \frac{-log(1-coverage)}{T}$, where coverage represents the targeted proportion of people vaccinated by the end of the roll-out period and \textit{T} represents the roll-out period.

Vaccination is assumed to have two mechanisms of effect: 1) prevention of infection and 2) protection against progressing to severe infection among those infected. A particular vaccine roll-out programme can be simulated to act through these two mechanisms simultaneously. The proportion of the effect that is attributed to preventing infection, $V_p = V_iV_e$ , where $V_i$ $\in [0,1]$ is the infection prevention efficacy and $V_e$ $\in [0,1]$ is the overall efficacy (that would be observed in clinical trials). If severity prevention efficacy is denoted $V_s$, since $V_e =V_i+V_s(1-V_i)$ it follows that $V_s =\frac {V_e(1-V_p)} {1- V_p V_e}$ . For the component of the vaccine effect attributed to infection prevention,
the infection risk of vaccinated individuals is reduced by ($1-V_i$). Severity-preventing vaccination reduces the infection fatality rate (IFR) and the probability that an infected individual experiences symptomatic disease. Thus, the vaccine efficacy parameter pertaining to disease severity prevention modifies the splitting proportions of infected individuals between the different clinical categories and the rate of COVID-19-related mortality.


\subsection{Contact matrices construction}
\label{matrix_construction}
For each location $L$ (home, school, work, other locations) the age-specific contact matrix $\mathbf{C^L} = (c_{i,j}^L) \in \mathbb{R}_{+}^{16 \times 16}$ is defined such that $c_{i,j}^L$ is the average number of contacts that a typical individual aged $i$ has with individuals aged $j$. As there is no contact survey available for Australia that is complete across all age groups, the matrices $\mathbf{C^L}$ were obtained by extrapolating contact matrices from the United Kingdom, being a country included in the POLYMOD study in 2005 \cite{RN141}. The original matrices from the United Kingdom are denoted $\mathbf{Q^L} = (q_{i,j}^L) \in \mathbb{R}_{+}^{16 \times 16}$, where $q_{i,j}^L$ is defined using the same convention as for $c_{i,j}^L$. The matrices $\mathbf{Q^L}$ were extracted using the R package ``socialmixr'' (v 0.1.8) and then adjusted to account for age distribution differences between Victoria and the United Kingdom.

Let $\pi_j$ denote the proportion of people aged $j$ in Victoria, and $\rho_j$ the proportion of people aged $j$ in the United Kingdom. The contact matrices $\mathbf{C^L}$ were obtained from:
$$
c_{i,j}^L = q_{i,j}^L \times \frac{\pi_j}{\rho_j} .
$$


\section*{Problem 2 Solution}

Since we are assuming no scattering, at any given time $t$ there are three possible ``fates'' of our neutron in the next infinitesimal timestep, $dt$. These are (1) the particle continues with no decay or interaction, (2) the neutron decays, or (3) the neutron is absorbed. We want to find the probability that, given a destructive event has taken place (situation 2 or 3), the event was decay, rather than absorption. Formally, we write this as
$$ \text{p}(E=d | E \in \{d,a\}) $$

which we read as ``the instantaneous probability that an event is decay, given the event was decay or absorption.'' Statistically this is equivalent to
\begin{equation}
\label{prob}
\frac{\text{p}(E=d)}{\text{p}(E \in \{d,a\}} \text{ or } \frac{\text{p}(d)}{\text{p}(d) + \text{p}(a)}.
\end{equation}
(If you're not comfortable with the statistics here, you can reason through this intuitively. We have some event occuring, being either a decay or an absorption collision. The probability of that event depends on the individual probabilities of the independent events, decay and absorption. The probability of that event being a decay is just the fraction of the event's total probability that is attributable to the decay.)

From here on, we will write the argument of the probality function as a subscript, which will allow us to note the probability's dependence on either time or space. (For example, $\text{p}(d) \rightarrow \text{p}_d$.)

Now, we know that the exponential decay law is $N(t) = N_0 e^{-\lambda t}$. The probability that a neutron decays in some time $t$ is then
$$ P_d(t) = 1-\frac{N(t)}{N_0} = 1-e^{-\lambda t} $$
We can calculate that the instantantaneous probability that a neutron decays between times $t$ and $t+dt$ is
$$ \frac{dP_d(t)}{dt} = \lambda e^{-\lambda t} $$
From this equation, we note that $dP_d(t) = p_d(t)dt$. Remember, $P_d(t)$ is the total probability of decay, and so $p_d(t)$ is the instantaneous probability of decay per time. When multiplied by $dt$, this is $\text{p}_d(t)$.
$$ \text{p}_d(t) = p_d(t) \, dt = \lambda e^{-\lambda t} dt $$
We rewrite this equation in terms of $N(t)$, and
$$ \text{p}_d(t) = \frac{\lambda N(t)}{N_0} dt$$

Additionally, we know that the attenuation of neutrons moving through a material also follows an exponential function. The number of neutrons remaining after traveling through a material with macroscopic absorption cross section $\Sigma_a$, is
$$ N(x) = N_0 e^{-\Sigma_a x} $$
(note: $\Sigma_a = \sigma_a n$, where $\sigma_a$ is the microscopic absorption cross section and $n$ is the number density of the material in question)

We repeat the procedure from above, but now in space rather than time. The probability for a collision is
$$ P_a(x) = 1-\frac{N(x)}{N_0} = 1 - e^{-\Sigma_a x} $$
and the instantaneous probability is
$$ \frac{dP_a(x)}{dt} = \Sigma_a e^{\Sigma_a x} $$
or
$$ \text{p}_a(x) = p_a(x) \, dx = \Sigma_a e^{\Sigma_a x} dx .$$
Again, eliminating $dx$ and writing in terms of $N(x)$, we have
$$ \text{p}_a(x) = \frac{\Sigma_a N(x)}{N_0} dx $$
Now, we observe that using $\text{p}_d(t)$ and $\text{p}_a(x)$ in equation (\ref{prob}) causes all terms to be dependent on $N$, the number of neutrons. Unfortunately, we have $p_d$ reliant on $N(t)$, the number of neutrons surviving until time $t$, and $\text{p}_a$ reliant on $N(x)$, the number of neutrons reaching distance $x$. We are told, however, that these neutrons are thermal, and so are moving at $v = 2200$m/s. If we say $dx = v \, dt$, then we can rewrite $N(x) dx$ as a function of time!
$$ N(x) \, dx = N(t) v \, dt $$
and
$$ \text{p}_a(t) = \frac{\Sigma_a N(t) v}{N_0} dt $$
Finally, we do substitute this into equation (\ref{prob}), and get
\begin{align*}
\text{p}(E=d | E \in \{d,a\})	&= \frac{\frac{\lambda N(t)}{N_0} dt}{\frac{\lambda N(t)}{N_0} dt + \frac{\Sigma_a N(t) v}{N_0} dt}\\
								&= \frac{\lambda}{\lambda + \Sigma_a v}\\
								&= \left(1 + \frac{\Sigma_a v}{\lambda}\right)^{-1}\\
\end{align*}
We can look up $\Sigma_a$ to find it is approximately $0.022\text{ cm}^{-1}$ (or $2.2\text{ m}^{-1}$, and can calculate that 10.2 minutes is 612 seconds.  Using this, along with $v = 2200$ m/s, and $\lambda = \frac{\ln 2}{612} = 1.13\times10^{-3}\text{ s}^{-1}$, we can find the probability.
$$ \text{p}(E=d | E \in \{d,a\}) = \left(1 + \frac{(2.2\text{ m}^{-1})(2200\text{ m/s})}{1.13\times10^{-3}\text{ s}^{-1}}\right)^{-1} $$
$$\boxed{ \text{p}(E=d | E \in \{d,a\}) = 2.33\times10^{-7} }$$


\chapter{Number Theory}

\section{Misc}

\subsection{Geometric Series}
The geometric series is defined as
\begin{align}
	\sum_{n=0}^{N-1} ar^n =a\Big( \frac{1-r^{N}}{1-r}\Big)
\end{align}
Which is only convergent for $r < 1$. To prove it, let's call whatever the value of the total series is equal to $s$, so we have
\begin{align}
	s = a + ar + ar^2 + ar^3 + ... + ar^{N-1}
\end{align}
Let's multiply it by $r$
\begin{align}
	rs =  ar + ar^2 + ar^3 + ... + ar^{N}
\end{align}
We recognize that the portion on the right is basically the same as the earlier expression for $s$, so let's plug in exactly what that is
\begin{align}
	rs = (s - a) + ar^N
\end{align}
Rearranging this, we find
\begin{align}
	(r-1)s = a(r^N - 1)
\end{align}
Dividing through, we see that
\begin{align}
	\sum_{n=0}^{N-1} ar^n = s = a\Big( \frac{1-r^{N}}{1-r}\Big)
\end{align}

\subsection{Completing the Square}
If we have some function that looks like
\begin{align}
ax^2 + bx + c
\end{align}
and we want it to look like
\begin{align}
d(x+e)^2 + f
\end{align}
We have that
\begin{align}
ax^2 + bx + c = dx^2 + 2ed x + de^2 + f
\end{align}
Matching powers of $x$, we get that
\begin{align}
a &= d\\
b &= 2ed\\
c &= de^2+f
\end{align}
Solving these gives us
\begin{align}
d = a && e =\frac{b}{2a}  && f = c-\frac{b^2}{4a}
\end{align}

\subsection{Trigonometric Identities}

\begin{align}
\sin(\alpha\pm\beta) = \sin\alpha\cos\beta\pm\cos\alpha\sin\beta\\
\cos(\alpha\pm\beta) = \cos\alpha\cos\beta\mp\sin\alpha\sin\beta
\end{align}

With these identities we can derive the double angle formula, setting $\alpha = \beta$ so
\begin{align}
\cos2\alpha &= \cos^2\alpha -\sin^2\alpha\\
&= 2\cos^2\alpha-1
\end{align}
The Law of Cosines is
\begin{align}
c^2 = a^2 + b^2 -2ab\cos\theta
\end{align}
Where $\theta$ is the angle between $a$ and $b$. Can remember this because reduces to the Pythagorean Theorem for $\theta = \pi/2$ and when $\theta = \pi$ we have
\begin{align}
c^2 = a^2 + b^2 +2ab = (a+b)^2
\end{align}
A much simpler way to recover this same identity is to draw out the vectors themselves
\begin{align}
	\textbf{a} + \textbf{c} = \textbf{b} \rightarrow \textbf{c} = \textbf{a} - \textbf{b}
\end{align}
Looking at the square of this, we have
\begin{align}
	c^2 &= a^2 + b^2 - 2\textbf{a}\cdot\textbf{b}\\
	&= a^2 + b^2 -2ab\cos\theta
\end{align}

You can always remember the derivatives of a trigonometric function by looking at it's Taylor expansion, and taking the derivative of that
\begin{align}
	\sin x &= x - \frac{x^3}{3!} + \frac{x^5}{5!} + ...\\
	\cos x &= 1 - \frac{x^2}{2!} + \frac{x^4}{41} + ...
\end{align}
Taking the derivative of sin for instances gives us
\begin{align}
	\frac{d}{dx}\sin x &= \frac{d}{dx}\Big( x - \frac{x^3}{3!} + \frac{x^5}{5!} + ...\Big)\\
	&= 1 - \frac{x^2}{2!} + \frac{x^4}{41} + ...\\
	&= \cos x
\end{align}

\subsection{Polynomial Algebra}

Can find roots of polynomial equations with
$$
\begin{array}{rc@{}c@{}c@{}c@{}}
& -x^2 +& x + &2 & \\ \cline{2-4}
\multicolumn{1}{r|}{x+1} &-x^3+ & 0 + & 3x +&2\\
-&-x^2 -&x  &\\ \cline{2-3}
& 0 +& x^2 &\\
-&  & x^2 +&x\\ \cline{3-4}
& & 0 +&2x &\\
-& &  &2x +&2\\ \cline{4-5}
& & & &0\\
\end{array}
$$

\section{Combinatorics}
A critical combinatorics formula is
\begin{align}
{{n}\choose{k}} = \frac{n!}{k!(n-k)!}
\end{align}
Which tells us how may ways we can pick $k$ objects out of a total of $n$ of them. Obviously we should have $n>k$, so the number is positive, which means we should have $n$ on the top.

\subsection{Euclidean Algorithm}

If you have two numbers that you don't know the prime factorization of, one can find their greatest common denominator (qcd) using this algorithm.
\begin{enumerate}
\item Choose two numbers $N_1, N_2$
\begin{itemize}
\item	e.g. $57, 27$
\end{itemize}
\item Subtract the smaller of the two from the larger $\max(N_1,N_2) -\min(N_1,N_2)$
\begin{itemize}
\item	$57 -27 = 30$
\end{itemize}
\item Continue to subtract $\min(N_1,N_2)$ until you're about to get negative numbers
\begin{itemize}
\item $30 -27 = 3$
\end{itemize}
\item This number is the greatest common denominator of the two
\begin{itemize}
\item $3\times 19 = 57$
\item $3 \times 9 = 27$
\end{itemize}
\end{enumerate}

\subsection{Modular Arthimetic}
TODO

\section{Distributions}
\subsection{Binomial Distribution}
The Binomial distribution is given by
\begin{align}
P(k;n,p) = \begin{pmatrix}
n\\
k
\end{pmatrix}p^k(1-p)^{n-k}
\end{align}
Where
\begin{align}
\begin{pmatrix}
n\\
k
\end{pmatrix} = \frac{n!}{k!(n-k)!}
\end{align}
Which tells us, if we try something $n$ times, each of which has a chance $p$ of succeeding, that we get $k$ successes.

\subsection{Poisson Distribution}
The Poisson distribution is used to describe the distribution of discrete events over a given time or space interval. Consider a radioactive decay process which has $\lambda$ decays per minute.

For a process which obey's Binomial statistics, we have a set amount of times the event could happen $n$ and a proportion of successes $k$. For a Poisson process the time or space interval could in principle be broken up infinitely, making it such that we don't just count over a set number of dice rolls, effectively infinitely many of them. Thus we take the limit $n\rightarrow \infty$ of the Binomial distribution with
\begin{align}
p = \frac{\lambda}{n}
\end{align}
Which tells us that the probability of the event happening at any given time is $0$, but as we will see, will give us a property such that a finite amount of events are seen when we are done counting. Mathematically we find

\begin{align}
P(k; \mu) &= \lim_{n\to \infty} \frac{n(n-1)(n-2)...(n-k+1)}{k!}\left(\frac{\lambda}{n}\right)^k\left(1-\frac{\lambda}{n}\right)^{n-k}\\
&= \lim_{n\to \infty}\frac{n^k}{k!}\frac{\lambda^k}{n^k}\left(1-\frac{\lambda}{n}\right)^{n-k}
\end{align}
Using the definition of the exponential function we arrive at the Poisson distribution with
\begin{align}
P(k; \lambda) = \frac{\lambda^ke^{-\lambda}}{k!}
\end{align}

Thus the Poisson distribution is a limiting case of the Binomial distribution when the number of dice rolls is infinite, but the amount of events we observe remain finite.

In counting experiments, it is often useful to know that if 0 events are observed coming from a Poisson distribution, the one-sided 95\% upper limit on the number of events is $\approx 3$, which is consistent with
\begin{align}
	\frac{3^0e^{-3}}{0!} \approx 0.05
\end{align}
Since the confidence interval tells us a model with true parameter $\lambda=3$ has a 5\% chance to see 0 events. In particle physics, $\lambda=3$ is held as a the benchmark for if your theory is testable or not, if $\lambda < 3$ you have a large chance that even if your theory is correct, you would still see nothing.

\subsection{Gaussian Distribution}
Another distribution shows up in the case where $\lambda$ becomes so large that Stirling's approximation (Section \ref{stirling}) becomes valid. If we take a Poisson distribution with  $k = \lambda(1+\delta) \equiv x$ with $\lambda \gg 1, \delta \ll 1$ we can write
\begin{align}
	P(x; \lambda) &= \frac{\lambda^xe^{-\lambda}}{x!}\\
	&= \frac{\lambda^{\lambda(1+\delta)}e^{-\lambda}}{\lambda(1+\delta)!}
\end{align}
Using Stirling's approximation, one has
\begin{align}
		P(x; \lambda) &\approx \frac{\lambda^{\lambda(1+\delta)}e^{-\lambda}}{\sqrt{2\pi}e^{-\lambda(1+\delta)}(\lambda(1+\delta))^{\lambda(1+\delta)+1/2}}\\
		&\approx \frac{e^{-\lambda\delta}}{\sqrt{2\pi\lambda}} (1+\delta)^{-\lambda(1+\delta)-1/2}
\end{align}
Expanding the last term around $\delta=0$, we have
\begin{align}
	(1+\delta)^{-\lambda(1+\delta)-1/2} &\approx 1 + \delta*(\lambda+1/2) + \dots
\end{align}
TODO

In summary:
\begin{itemize}
	\item Poisson is limit of binomial for $p$ small and $n\gg \mu$
	\item Gaussian is limit of Poisson for large $\mu$
	\item Gaussian is limit of binomial for large $\mu=np$
\end{itemize}


\section{Applications of the determinant}

\begin{outcome}
  \begin{enumerate}
  \item Use determinants to determine whether a matrix has an inverse,
    and evaluate the inverse using cofactors.
  \item Apply Cramer's rule to solve a $2\times 2$ or a $3\times 3$
    linear system.
  \item Given data points, find an appropriate interpolating
    polynomial and use it to estimate points.
  \end{enumerate}
\end{outcome}


\lab{A Pseudospectral method for periodic functions}{A Pseudospectral method for periodic functions}
\label{lab:pseudospectral2}

\objective{
% We study traveling wave solutions of the Korteweg-de Vries (KdV) equation.
We look at a pseudospectral method with a Fourier basis, and numerically solve the advection equation using a pseudospectral discretization in space and a Runge-Kutta integration scheme in time.  }

% \section{A Pseudospectral method for periodic functions}
Let $f$ be a periodic function on $[0,2\pi]$. Let $x_1,\ldots,x_N$ be $N$ evenly spaced grid points on $[0,2\pi].$ Since $f$ is periodic on $[0,2\pi]$, we can ignore the grid point $x_0 = 0$. We will further assume that $N$ is even; similar formulas can be derived for $N$ odd. Let $h = 2\pi/N$; then $\{x_1,\ldots,x_N\} = \{h,2h,\ldots,2\pi-h,2\pi\}$.

The discrete Fourier transform (DFT) of $f$, denoted by $\hat{f}$ or $\mathcal{F}(f)$, is given by
\[
\hat{f}(k) = h \sum_{j=1}^N e^{-ikx_j}f(x_j) \quad \text{ where } k = -N/2+1, \ldots,0,1,\ldots, N/2.
\]
The inverse DFT is then given by
\begin{align}
\begin{split}
f(x_j) &= \frac{1}{2\pi}\sum_{k=-N/2}^{N/2}\frac{e^{ikx_j}}{c_k}\hat{f}(k), \quad j = 1,\ldots, N,
% \\
% &= \frac{1}{2\pi}\sum_{k=-N/2}^{N/2}\!\!{}^{'} e^{ikx_j}\hat{f}(k), \quad j = 1,\ldots, N,
\end{split}\label{inverse_dft}
\end{align}
where %$\sum_{k=-N/2}^{N/2}\!\!{}^{'}$ is used to denote...
\begin{align}
	c_k = \begin{cases} 2 & \text{if }k = -N/2 \text{ or }k = N/2, \\ 1 &  \text{otherwise.}
\end{cases}
\end{align}
The inverse DFT can then be used to define a natural interpolant (sometimes called a band-limited interpolant) by evaluating (\ref{inverse_dft}) at any $x$ rather than $x_j$:
\begin{align}
p(x) = \frac{1}{2\pi}\sum_{k=-N/2}^{N/2} e^{ikx}\hat{f}(k). \label{interpolant}
\end{align}
The interpolant for $f'$ is then given by
\begin{align}
p'(x) = ik \frac{1}{2\pi}\sum_{k=-N/2+1}^{N/2-1} e^{ikx}\hat{f}(k). \label{spectral2:deriv}
\end{align}

Consider the function $u(x) = \sin^2 (x) \cos(x) +e^{2\sin(x+1)}$.
Using \eqref{spectral2:deriv}, the derivative $u'$ may be approximated with the following code.  \footnote{See \textit{Spectral Methods in MATLAB} by Lloyd N. Trefethen.  Another good reference is \textit{Chebyshev and Fourier Spectral Methods} by John P. Boyd.}
We note that although we only approximate $u'$ at the Fourier grid points, \eqref{spectral2:deriv} provides an analytic approximation of $u'$ in the form of a trigonometric polynomial.

\begin{lstlisting}
import numpy as np
from scipy.fftpack import fft, ifft
import matplotlib.pyplot as plt

N=24
x1 = (2.*np.pi/N)*np.arange(1,N+1)
f = np.sin(x1)**2.*np.cos(x1) + np.exp(2.*np.sin(x1+1))

k = np.concatenate(( np.arange(0,N/2) ,
					 np.array([0])	, # Because hat{f}'(k) at k = N/2 is zero.
					 np.arange(-N/2+1,0,1)	))

# Approximates the derivative using the pseudospectral method
f_hat = fft(f)
fp_hat = ((1j*k)*f_hat)
fp = np.real(ifft(fp_hat))

# Calculates the derivative analytically
x2 = np.linspace(0,2*np.pi,200)
derivative = (2.*np.sin(x2)*np.cos(x2)**2. -
				np.sin(x2)**3. +
				2*np.cos(x2+1)*np.exp(2*np.sin(x2+1))
				)

plt.plot(x2,derivative,'-k',linewidth=2.)
plt.plot(x1,fp,'*b')
plt.savefig('spectral2_derivative.pdf')
plt.show()

\end{lstlisting}

\begin{figure}
\centering
\includegraphics[width=\textwidth]{spectral2_derivative.pdf}
\caption{The derivative of $u(x) = \sin^2 (x) \cos(x) +e^{2\sin(x+1)}$.}
\label{fig:spectral:spectral2_derivative}
\end{figure}

\begin{problem}
Consider again the function $u(x) = \sin^2 (x) \cos(x) +e^{2\sin(x+1)}$.
Create a function that approximates $\frac{1}{2}u''-u'$ on the Fourier grid points for a given $N$.
\end{problem}

% \begin{lstlisting}
% import numpy as np
% import matplotlib.pyplot as plt
%
% # Solve the ODE $u_{xx} = e^u,$ with boundary conditions
% #  $u(0) = u(2\pi) = 0$
%
%
% \end{lstlisting}

% \begin{problem}
% The motion of a damped pendulum can be described by the ODE
% 	\begin{align}
% 	\theta'' + \theta' +\sin \theta = 0. \label{damped_pendulum}
% 	\end{align}
% Using the pseudospectral method, solve \eqref{damped_pendulum} on the interval $[0,2\pi]$, with the boundary conditions $\theta(0) = \theta(2\pi) =0$. Produce at least two unique solutions.
% \end{problem}

% \section{The KdV equation}
%
% There are canonical model equations for various types of phenomena.  Long, small amplitude waves moving in one direction can generally be described by the  Korteweg-de Vries (KdV) equation. The KdV equation is given by
% \[  \frac{\partial u }{\partial t} + u \frac{\partial u}{\partial x} + \frac{\partial^3 u}{\partial x^3} = 0.
% \]
%
% The KdV equation possesses traveling wave solutions called solitary waves. These traveling waves have the form
% \[ u(x,t) = 3\alpha^2 \sech^2(\alpha(x-x_0)/2 - \alpha^3 t).
% \]
%
% History of solitons: first observed by John Scott Russell in 1834.
% Solution form:
% Interaction of solitons:
%
% Solitons versus solitary waves. I believe solitary waves are solitons in a fluid dynamics context.
% John Russell

\section*{The advection equation}
Recall that the advection equation is given by
\begin{align}
&{ }u_t + cu_x = 0
\end{align}
where $c$ is the speed of the wave (the wave travels to the right for $c > 0$).
We will consider the solution of the advection equation on the circle; this essentially amounts to solving the advection equation on $[0,2\pi]$ and assuming periodic boundary conditions.

A common method for solving time-dependent PDEs is called the \textit{method of lines}. To apply the method of lines to our problem, we use our Fourier grid points in $[0,\pi]$: given an even $N$, let $h = 2\pi/N$, so that $\{x_1,\ldots,x_N\} = \{h,2h,\ldots,2\pi-h,2\pi\}$.  By using these grid points we obtain the collection of equations
\begin{align}
&{ }u_t(x_j,t) + cu_x(x_j,t) = 0, \quad t >0, \quad j = 1, \ldots N. \label{spectral2:method_oflines}
\end{align}

Let $U(t)$ be the vector valued function given by $U(t) = (u(x_j,t))_{j=1}^N$.
Let $\mathcal{F}(U)(t)$ denote the discrete Fourier transform of $u(x,t)$ (in space), so that
\[
\mathcal{F}(U)(t) = (\hat{u}(k,t))_{k=-N/2+1}^{N/2}.
\]
Define $\mathcal{F}^{-1}$ similarly.
Using the pseudospectral approximation in space leads to the system of ODEs
\begin{align}
	U_t +  \vec{c}\mathcal{F}^{-1}\left(i\vec{k}\mathcal{F}(U) \right) = 0
\end{align}
where $\vec{k}$ is a vector, and $\vec{k}\mathcal{F}(U) $ denotes element-wise multiplication.
Similarly $\vec{c}$ could also be a vector, if the wave speed $c$ is allowed to vary.

\begin{problem}
	Using a fourth order Runge-Kutta method (RK4), solve the initial value problem
	\begin{align}
		u_t +c(x) u_x = 0,
	\end{align}
	where $c(x) = .2 + \sin^2(x-1)$, and $u(x,t=0) = e^{-100(x-1)^2}.$  Plot your numerical solution from $t = 0$ to $t = 8$.  Note that the initial data is nearly zero near $x = 0$ and  $2 \pi$, and so we can use the pseudospectral method. \footnote{This problem is solved in \textit{Spectral Methods in MATLAB} using a leapfrog discretization in time. }
	\label{spectral2:advection_equation}
\end{problem}

\begin{figure}
\centering
\includegraphics[width=\textwidth]{advection.png}
\caption{The solution of the variable speed advection equation; see Problem  \ref{spectral2:advection_equation}.}
\label{fig:spectral:spectral2_advection}
\end{figure}


\documentclass{article}

\usepackage{amsmath} % allows you to put text in the math environment.

\begin{document}

\title{Some Examples of Equation-Writing in \LaTeX}
\author{Doreen De Leon\\Department of Mathematics, UCLA}
\date{December 20, 2002}
\maketitle

\section{Writing a Simple Equation}
\label{sec:simple}
\setcounter{equation}{0} % sets equation counter to 1

To display an unnumbered equation on a new line, just type:
\emph{$\backslash$[ x' = 2x - 3 $\backslash$]}.  This will display as:
\[ x' = 2x - 3 \]
If we want to get a numbered equation, we must type:\\
\emph{$\backslash$begin\{equation\}\\x' = 2x - 3\\$\backslash$end\{equation}\}.
This will display as:
\begin{equation}
x' = 2x - 3
\end{equation}

Now, suppose we want to write a differential equation in another form.
Try, \emph{$\backslash$[$ \backslash$frac\{dy\}\{dt\} = 2y + 8 $\backslash$]}.
This displays as:
\[ \frac{dy}{dt} = 2y + 8 \]
or, we may write \emph{\$\$ y\_t = 2y + 8\$\$}:
$$ y_t = 2y + 8 $$

Now, suppose we have a partial differential equation.
To write it with the partial derivatives, we just do:\\
\emph{\$\$ $\backslash$frac\{$\backslash$partial\^2 u\}
    \{$\backslash$partial\^2 x\} + $\backslash$frac\{$\backslash$partial\^2 u\}
    \{$\backslash$partial\^2 y\} = 0 \$\$}.
This displays as:
$$ \frac{\partial^2 u}{\partial^2 x} +
\frac{\partial^2 u}{\partial^2 y} = 0 $$
Or, we may write \emph{\$\$ u\_\{xx\} + u\_\{yy\} = 0 \$\$}, which displays as:
$$ u_{xx} + u_{yy} = 0 $$

To add text to an equation do for example,:\\
\emph{\$\$ y=mx+b, $\backslash$text\{ where \$m\$ is the slope, \} x
      $\backslash$in (-$\backslash$infty, $\backslash$infty) \$\$}.
This displays as:
$$ y=mx+b, \text{ where $m$ is the slope, } x \in (-\infty, \infty) $$.
Note: You need to have included the \texttt{amstext} package at the beginning
of the document (after the \emph{$\backslash$documentclass} command.

If we want to write an equation with a two-line right-hand-side,
\begin{equation}
y(0) = \left\{ \begin{array}{cc}
              1 & \mbox{if $x \le 0$, }\\
              -1 & \mbox{if $x > 0$.}
             \end{array} \right.
\end{equation}

% Note:  The single dollar sign puts us into math mode.  The double dollar
% sign puts us into the equation mode.

To write several equations together, we do the following:
\begin{eqnarray}
\label{eqn:wave}
u_t + u_x & = & 0 \nonumber \\
u(x, 0) & = & \left\{ \begin{array}{cc}
              1 & \mbox{if $x \le 0$, }\\
              -1 & \mbox{if $x > 0$.}
             \end{array} \right.
\end{eqnarray}

\section{More complicated expressions}
\label{comp}
\setcounter{equation}{0}

Here is how we would write a matrix:
$ A = \left( \begin{array}{ccc} a_{11} \hspace{1mm} a_{12} \hspace{1mm}
                                    \ldots \hspace{1mm} a_{1n} \\
                              a_{21} \hspace{1mm} a_{22} \hspace{1mm}
                                     \ldots \hspace{1mm} a_{2n} \\
                              \vdots \hspace{6mm} \vdots \hspace{11mm} \vdots \\
                              a_{n1} \hspace{1mm} a_{n2} \hspace{1mm}
                                     \ldots \hspace{1mm} a_{nn}
              \end{array}  \right) $

To write a system of equations:
\begin{equation}
\label{eq:pred}
\left\{  \begin{array}{c}
                        x'  =  3x - 2y + 3xy, \nonumber \\
                        y'  =  2x - 3y - 2xy, \\
                        x(0)  =  0, \nonumber \\
                        y(0)  =  1 \nonumber
           \end{array}  \right.
\end{equation}

\end{document}


\section{Constraint Logic Programming}
\label{sec:constr-logic-progr}

Prolog is based on unification. Data of the program are terms, and
unification solves equations between terms. A natural extension to
this is to allow for other types of equations, for example, arithmetic
equations, inequations, or disequations. This is what Constraint Logic
Programming (CLP) does, providing the mechanisms to solve arithmetic
constraints. See~\cite{marriot-stuckey-98} for a good introduction to
CLP.

The Ciao packages for CLP allow for constraints over arithmetic
expressions. Constraints include equations, inequations, and
disequations. Constraints are expressed using the operators:
\begin{quote}
\begin{verbatim}
.=.   .<>.   .<.   .=<.   .>.   .>=.
\end{verbatim}
\end{quote}
%
for equalities (\verb+.=.+), inequalities (\verb+.<>.+), and
disequalities between two arithmetic expressions.
%
Expressions are built with the usual arithmetic operators, numbers,
and variables.
%
For example:
\begin{quote}
\begin{verbatim}
... :- ..., X+Y .=. 5, X-Y .=. 2, ...
\end{verbatim}
\end{quote}
%
sets up a system of equations that CLP will solve, yielding:
\begin{quote}
\begin{verbatim}
Y .=. 1.5,
X .=. 3.5
\end{verbatim}
\end{quote}
%
and the disequalities:
\begin{quote}
\begin{verbatim}
... :- ..., X+Y .>=. 5, X-Y .=<. 2, ...
\end{verbatim}
\end{quote}
%
set up a system of disequations, the solution of which can only be
parametric (because there is not a unique solution). CLP will yield:
\begin{quote}
\begin{verbatim}
X. >=. 5.0-Y,
X .=<. 2.0+Y
\end{verbatim}
\end{quote}
%
in this case. Note how variable \verb+Y+ acts as a parameter of the
solution. Once a value is assigned to \verb+Y+, the value(s) of \verb+X+
is determined by the above solution inequations. For example:
\begin{quote}
\begin{verbatim}
... :- ..., X+Y .>=. 5, X-Y .=<. 2, ..., Y .=. 0, ...
\end{verbatim}
\end{quote}
%
makes CLP answer ``no'', because for a value 0 for \verb+Y+ there are
no values for \verb+X+ that satisfy the inequations. However:
\begin{quote}
\begin{verbatim}
... :- ..., X+Y .>=. 5, X-Y .=<. 2, ..., Y .=. 2, ...
\end{verbatim}
\end{quote}
%
yields:
\begin{quote}
\begin{verbatim}
X.>=.3.0,
X.=<.4.0,
Y.=.2.0
\end{verbatim}
\end{quote}
%
since any real number between (and including) 3 and 4 satisfies the
solution.

You can mix equations, inequations, and disequations arbitrarily. You
can also mix constraints with the classical unification and Prolog
arithmetic operator \verb+arithmetic:is/2+.

However, note that unification manipulates terms, which include
numbers and expressions that may ``look like'' arithmetic expressions,
but are not evaluated. Thus:
\begin{quote}
\begin{verbatim}
... :- ..., X+Y .>=. 5, X-Y .=<. 2, ..., Y = 2, ...
\end{verbatim}
\end{quote}
%
yields the same solution as above, but:
\begin{quote}
\begin{verbatim}
... :- ..., X+Y .>=. 5, X-Y .=<. 2, ..., Y = 1+1, ...
\end{verbatim}
\end{quote}
%
fails, since \verb-1+1- is not a number, and can not participate in
expressions involved in constraints.

The particular domain of numbers which can be involved in constraints
conditions the particular constraint system used. Thus, for real numbers,
rational numbers, and (finite ranges of) integer numbers, we have
CLP(R), CLP(Q), and CLP(FD) (for Finite Domains), respectively.

Each of the constraint systems mentioned corresponds to a
package. They are revised in the following, but please consult the
Ciao reference manual for each package for details on the constraints
and the operators that can be used in the expressions appearing in the
constraints for each system.

\subsection{Constraints over Reals}

The package \verb+clpr+ enables CLP(R), which allows for constraints
over real numbers. This means that the solutions for the variables
involved in constraints are real numbers, and all numbers used in the
expressions in constraints are considered real numbers.

The internal representation of real numbers may cause losses of
precision. For example,
\begin{quote}
\begin{verbatim}
?- X+Y .>=. 3, X=0.1.

Y.>=.2.9,
X.=.0.100000000000000089 ?
\end{verbatim}
\end{quote}

\comment{Incomplete}

\subsection{Constraints over Rationals}

The package \verb+clpq+ enables CLP(Q), which allows for constraints
over rational numbers. This means that the solutions for the variables
involved in constraints are rational numbers, and all numbers used in the
expressions in constraints are considered rational.

The internal representation of rational numbers allows for infinite
precision. For example,
\begin{quote}
\begin{verbatim}
?- X+Y .>=. 3, X=0.1.

X = 1/10,
Y.>=.29/10 ?
\end{verbatim}
\end{quote}

\comment{The output {\tt X = 1/10} is incorrect!!!}

\comment{Incomplete}

The conversion of reals to rationals...

\subsection{Finite Domain Constraints}

\comment{Still under construction}


\chapter{Derivation of implicit backwards difference formulae}
\label{cha:deriv-impl-backw}

Starting from \cref{eq:59} and setting $\pv_k(t_{n+1}) = \ffv{t_{n+1}, \yv_{n+1}}$ we obtain
\begin{equation}
  \begin{aligned}
    \fv(t_{n+1}, \yv_{n+1}) &= \sum_{j=1}^k \yv[t_{n+1}, \ldots, t_{n+1-j}] \sum_{l=0}^{j-1} \prod_{i=0, i \neq l}^{j-1} (t_{n+1} - t_{n+1-i}).
  \end{aligned}
\end{equation}
This can be greatly simplified by noticing that the product $ \prod_{i=0, i \neq l}^{j-1} (t_{n+1} - t_{n+1-i})$ is zero whenever it contains $i=0$, \ie all terms in the sum with $l \neq 0$.
This leaves us with
\begin{equation}
  \begin{aligned}
    \fv(t_{n+1}, \yv_{n+1}) &= \sum_{j=1}^k \yv[t_{n+1}, \ldots, t_{n+1-j}] \prod_{i=0, i \neq 0}^{j-1} (t_{n+1} - t_{n+1-i}), \\
    &=  \yv[t_{n+1}, t_n] + \sum_{j=2}^k \yv[t_{n+1}, \ldots, t_{n+1-j}] \prod_{i=1}^{j-1} (t_{n+1} - t_{n+1-i}). \\
  \end{aligned}
\end{equation}

For $k=1$ we get
\begin{equation}
  \begin{aligned}
    \fv(t_{n+1}, \yv_{n+1}) &= \frac{\yv_{n+1} - \yv_n}{\dtn}, \\
    \yv_{n+1} &= \yv_n + \dtn \fv(t_{n+1}, \yv_{n+1}),
  \end{aligned}
\end{equation}
which is backward Euler as expected.

For $k=2$
\begin{equation}
  \label{eqn:bdf2-derivation}
  \begin{aligned}
    \fv(t_{n+1}, \yv_{n+1}) &= \frac{\yv_{n+1} - \yv_n}{\dtn} +  \yv[t_{n+1}, t_{n}, t_{n-1}](t_{n+1} - t_n), \\
    &= \frac{\yv_{n+1} - \yv_n}{\dtn} +  \frac{\dtn}{\dtx{n+1} + \dtn} \bigb{\frac{\yv_{n+1} - \yv_n}{\dtn} - \frac{\yv_n - \yv_{n-1}}{\dtx{n-1}}}. \\
  \end{aligned}
\end{equation}
After some algebra this becomes
\begin{equation}
  \label{eqn:bdf2-derivation-rearranged}
  \begin{aligned}
    \frac{\yv_{n+1} - \yv_n}{\dtn} = \frac{\dtn}{2\dtn + \dtx{n-1}} \frac{\yv_n - \yv_{n-1}}{\dtx{n-1}}
    + \frac{\dtn + \dtx{n-1}}{2\dtn + \dtx{n-1}} \fv(t_{n+1}, \yv_{n+1}),
  \end{aligned}
\end{equation}
which is variable step BDF2 \cite[715]{GreshoSani}.

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


\hypertarget{group__numpp__roots}{}\section{Root Finding}
\label{group__numpp__roots}\index{Root Finding@{Root Finding}}

This module provides methods for finding roots of $f(x) = 0$.

\subsection*{Functions}
\begin{DoxyCompactItemize}
\item
{\footnotesize template$<$typename T , typename Func , typename  = std\+::enable\+\_\+if\+\_\+t$<$std\+::is\+\_\+floating\+\_\+point$<$\+T$>$\+::value$>$$>$ }\\constexpr auto \hyperlink{group__numpp__roots_ga8b5bb65b3192456c184a331f88af0b56}{numpp\+::roots\+::bisection} (Func \&\&f, T lower\+\_\+bound, T upper\+\_\+bound, std\+::size\+\_\+t iterations=1000)
\item
{\footnotesize template$<$typename T , typename Func $>$ }\\constexpr auto \hyperlink{group__numpp__roots_ga1b4f2040358e71ad1fd2bfcc8c71a8d6}{numpp\+::roots\+::bisection} (Func \&\&f, T \&\&lower\+\_\+bound, T \&\&upper\+\_\+bound, const double epsilon, std\+::size\+\_\+t iterations)
\item
{\footnotesize template$<$typename Function , typename Derivative , typename Second\+Derivative , typename T $>$ }\\constexpr auto \hyperlink{group__numpp__roots_ga30924012d656a67696860b51d3d3f315}{numpp\+::roots\+::halley} (T \&\&value, std\+::size\+\_\+t iterations=1000, const double epsilon=1e-\/7)
\item
{\footnotesize template$<$typename Function , typename Derivative , typename Second\+Derivative , typename T $>$ }\\constexpr auto \hyperlink{group__numpp__roots_gaa5dcba977340c78cd587fc7f9a3c0648}{numpp\+::roots\+::halley} (T \&\&value, Function f, Derivative df, Second\+Derivative dfdf, std\+::size\+\_\+t iterations=1000, const double epsilon=1e-\/7)
\item
{\footnotesize template$<$typename Function , typename Derivative , typename T $>$ }\\constexpr auto \hyperlink{group__numpp__roots_ga756a768c79701c5506809765b24f89a0}{numpp\+::roots\+::newton} (T \&\&value, std\+::size\+\_\+t iterations=1000, const double epsilon=1e-\/7)
\item
{\footnotesize template$<$typename Function , typename Derivative , typename T $>$ }\\constexpr auto \hyperlink{group__numpp__roots_ga0c3358cbe925f1840d2332f81dec42ab}{numpp\+::roots\+::newton} (Function \&\&f, Derivative \&\&df, T \&\&value, std\+::size\+\_\+t iterations=1000, const double epsilon=1e-\/7)
\item
{\footnotesize template$<$typename Function\+And\+Derivative , typename T $>$ }\\constexpr auto \hyperlink{group__numpp__roots_ga7784b72874be701ab11320a8ab594e6f}{numpp\+::roots\+::newton} (Function\+And\+Derivative \&\&f, T \&\&value, std\+::size\+\_\+t iterations=1000, const double epsilon=1e-\/7)
\end{DoxyCompactItemize}

\subsection{Detailed Description}
This module provides methods for finding roots of $f(x) = 0$.

Namespace\+:
\begin{DoxyCode}
\hyperlink{namespacenumpp_1_1roots}{numpp::roots}
\end{DoxyCode}

Include\+:
\begin{DoxyCode}
\hyperlink{namespacenumpp}{numpp}/roots.h #includes every method in the module
\hyperlink{namespacenumpp}{numpp}/roots/METHOD.hpp #include specific METHOD
\end{DoxyCode}

\subsection{Function Documentation}
\mbox{\Hypertarget{group__numpp__roots_ga8b5bb65b3192456c184a331f88af0b56}\label{group__numpp__roots_ga8b5bb65b3192456c184a331f88af0b56}}
\index{Root Finding@{Root Finding}!bisection@{bisection}}
\index{bisection@{bisection}!Root Finding@{Root Finding}}
\subsubsection{\texorpdfstring{bisection()}{bisection()}\hspace{0.1cm}{\footnotesize\ttfamily [1/2]}}
{\footnotesize\ttfamily template$<$typename T , typename Func , typename  = std\+::enable\+\_\+if\+\_\+t$<$std\+::is\+\_\+floating\+\_\+point$<$\+T$>$\+::value$>$$>$ \\
constexpr auto numpp\+::roots\+::bisection (\begin{DoxyParamCaption}\item[{Func \&\&}]{f,  }\item[{T}]{lower\+\_\+bound,  }\item[{T}]{upper\+\_\+bound,  }\item[{std\+::size\+\_\+t}]{iterations = {\ttfamily 1000} }\end{DoxyParamCaption})}

Bisects given interval and finds the root of function.

\begin{DoxyTemplParams}{Template Parameters}
{\em T} & type of interval arguments \\
\hline
{\em Func} & type of Function (auto-\/deduced Functor or function pointer)\\
\hline
\end{DoxyTemplParams}
Algorithm stops when it reaches automatically calculated precision or exceeds maximum number of iterations (default\+: 1000)

Precision adjusted to the lower and upper arguments, accordingly to Numerical Recipees recipe.\mbox{\Hypertarget{group__numpp__roots_ga1b4f2040358e71ad1fd2bfcc8c71a8d6}\label{group__numpp__roots_ga1b4f2040358e71ad1fd2bfcc8c71a8d6}}
\index{Root Finding@{Root Finding}!bisection@{bisection}}
\index{bisection@{bisection}!Root Finding@{Root Finding}}
\subsubsection{\texorpdfstring{bisection()}{bisection()}\hspace{0.1cm}{\footnotesize\ttfamily [2/2]}}
{\footnotesize\ttfamily template$<$typename T , typename Func $>$ \\
constexpr auto numpp\+::roots\+::bisection (\begin{DoxyParamCaption}\item[{Func \&\&}]{f,  }\item[{T \&\&}]{lower\+\_\+bound,  }\item[{T \&\&}]{upper\+\_\+bound,  }\item[{const double}]{epsilon,  }\item[{std\+::size\+\_\+t}]{iterations }\end{DoxyParamCaption})}

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Everything has to be specified by the user

Algorithm stops when it reaches precision given by epsilon or exceeds iterations provided by the user\mbox{\Hypertarget{group__numpp__roots_ga30924012d656a67696860b51d3d3f315}\label{group__numpp__roots_ga30924012d656a67696860b51d3d3f315}}
\index{Root Finding@{Root Finding}!halley@{halley}}
\index{halley@{halley}!Root Finding@{Root Finding}}
\subsubsection{\texorpdfstring{halley()}{halley()}\hspace{0.1cm}{\footnotesize\ttfamily [1/2]}}
{\footnotesize\ttfamily template$<$typename Function , typename Derivative , typename Second\+Derivative , typename T $>$ \\
constexpr auto numpp\+::roots\+::halley (\begin{DoxyParamCaption}\item[{T \&\&}]{value,  }\item[{std\+::size\+\_\+t}]{iterations = {\ttfamily 1000},  }\item[{const double}]{epsilon = {\ttfamily 1e-\/7} }\end{DoxyParamCaption})}

S\+Y\+M\+B\+O\+L\+I\+C\+AL O\+V\+E\+R\+L\+O\+AD\+:

Halley\textquotesingle{}s algorithm for finding root of the function using first and second order derivatives.

\begin{DoxyTemplParams}{Template Parameters}
{\em T} & type of function argument \\
\hline
{\em Function} & type of function (has to be symbolic, check\+: symbolic) \\
\hline
{\em Derivative} & type of derivative (has to be symbolic, check\+: symbolic) \\
\hline
{\em Second\+Derivative} & type of second derivative (has to be symbolic, check\+: symbolic)\\
\hline
\end{DoxyTemplParams}
\begin{DoxyWarning}{Warning}
Theorethically cubic convergence when $f'''$ continuous.

Some problems may arise for this method, check professional literature
\end{DoxyWarning}
Algorithm stops when it reaches given precision or exceeds maximum number of iterations (default\+: 1000)

\begin{DoxyReturn}{Returns}
{\bfseries Type}\+: Same as Function return type

{\bfseries Value}\+: Root in the case of convergence
\end{DoxyReturn}
\begin{DoxyWarning}{Warning}
{\bfseries May not converge to the root, evaluate your result after obtaining it}
\end{DoxyWarning}
\begin{DoxySeeAlso}{See also}
Symbolic Differentiation
\end{DoxySeeAlso}
\mbox{\Hypertarget{group__numpp__roots_gaa5dcba977340c78cd587fc7f9a3c0648}\label{group__numpp__roots_gaa5dcba977340c78cd587fc7f9a3c0648}}
\index{Root Finding@{Root Finding}!halley@{halley}}
\index{halley@{halley}!Root Finding@{Root Finding}}
\subsubsection{\texorpdfstring{halley()}{halley()}\hspace{0.1cm}{\footnotesize\ttfamily [2/2]}}
{\footnotesize\ttfamily template$<$typename Function , typename Derivative , typename Second\+Derivative , typename T $>$ \\
constexpr auto numpp\+::roots\+::halley (\begin{DoxyParamCaption}\item[{T \&\&}]{value,  }\item[{Function}]{f,  }\item[{Derivative}]{df,  }\item[{Second\+Derivative}]{dfdf,  }\item[{std\+::size\+\_\+t}]{iterations = {\ttfamily 1000},  }\item[{const double}]{epsilon = {\ttfamily 1e-\/7} }\end{DoxyParamCaption})}

F\+I\+N\+I\+TE D\+I\+F\+F\+E\+R\+E\+N\+C\+E/\+O\+T\+H\+ER M\+E\+T\+H\+O\+DS O\+V\+E\+R\+L\+O\+AD

\begin{DoxyTemplParams}{Template Parameters}
{\em T} & type of function argument \\
\hline
{\em Function} & type of function (Functor or function) \\
\hline
{\em Derivative} & type of derivative (Functor of function) \\
\hline
{\em Second\+Derivative} & type of second derivative (Functor or function)\\
\hline
\end{DoxyTemplParams}
\mbox{\Hypertarget{group__numpp__roots_ga756a768c79701c5506809765b24f89a0}\label{group__numpp__roots_ga756a768c79701c5506809765b24f89a0}}
\index{Root Finding@{Root Finding}!newton@{newton}}
\index{newton@{newton}!Root Finding@{Root Finding}}
\subsubsection{\texorpdfstring{newton()}{newton()}\hspace{0.1cm}{\footnotesize\ttfamily [1/3]}}
{\footnotesize\ttfamily template$<$typename Function , typename Derivative , typename T $>$ \\
constexpr auto numpp\+::roots\+::newton (\begin{DoxyParamCaption}\item[{T \&\&}]{value,  }\item[{std\+::size\+\_\+t}]{iterations = {\ttfamily 1000},  }\item[{const double}]{epsilon = {\ttfamily 1e-\/7} }\end{DoxyParamCaption})}

S\+Y\+M\+B\+O\+L\+I\+C\+AL O\+V\+E\+R\+L\+O\+AD

Newton\textquotesingle{}s algorithm for finding root of the function using first order derivative.

\begin{DoxyTemplParams}{Template Parameters}
{\em T} & type of function argument \\
\hline
{\em Function} & type of function (has to be symbolic, check\+: symbolic) \\
\hline
{\em Derivative} & type of derivative (has to be symbolic, check\+: symbolic)\\
\hline
\end{DoxyTemplParams}
\begin{DoxyWarning}{Warning}
Theorethically quadratic convergence when $f''$ continuous.

Some problems may arise for this method, check professional literature
\end{DoxyWarning}
Algorithm stops when it reaches given precision or exceeds maximum number of iterations (default\+: 1000)

\begin{DoxyReturn}{Returns}
{\bfseries Type}\+: Same as Function return type

{\bfseries Value}\+: Root in the case of convergence
\end{DoxyReturn}
\begin{DoxyWarning}{Warning}
{\bfseries May not converge to the root, evaluate your result after obtaining it}
\end{DoxyWarning}
\begin{DoxySeeAlso}{See also}
Symbolic Differentiation
\end{DoxySeeAlso}
\mbox{\Hypertarget{group__numpp__roots_ga0c3358cbe925f1840d2332f81dec42ab}\label{group__numpp__roots_ga0c3358cbe925f1840d2332f81dec42ab}}
\index{Root Finding@{Root Finding}!newton@{newton}}
\index{newton@{newton}!Root Finding@{Root Finding}}
\subsubsection{\texorpdfstring{newton()}{newton()}\hspace{0.1cm}{\footnotesize\ttfamily [2/3]}}
{\footnotesize\ttfamily template$<$typename Function , typename Derivative , typename T $>$ \\
constexpr auto numpp\+::roots\+::newton (\begin{DoxyParamCaption}\item[{Function \&\&}]{f,  }\item[{Derivative \&\&}]{df,  }\item[{T \&\&}]{value,  }\item[{std\+::size\+\_\+t}]{iterations = {\ttfamily 1000},  }\item[{const double}]{epsilon = {\ttfamily 1e-\/7} }\end{DoxyParamCaption})}

F\+U\+N\+C\+T\+O\+R/\+F\+U\+N\+C\+T\+I\+ON O\+V\+E\+R\+L\+O\+AD

\begin{DoxyTemplParams}{Template Parameters}
{\em T} & type of function argument \\
\hline
{\em Function} & type of function (Functor or function) \\
\hline
{\em Derivative} & type of derivative (Functor or function)\\
\hline
\end{DoxyTemplParams}
You may use finite difference code from differentiation module

\begin{DoxySeeAlso}{See also}
Finite Difference Differentiation
\end{DoxySeeAlso}
\mbox{\Hypertarget{group__numpp__roots_ga7784b72874be701ab11320a8ab594e6f}\label{group__numpp__roots_ga7784b72874be701ab11320a8ab594e6f}}
\index{Root Finding@{Root Finding}!newton@{newton}}
\index{newton@{newton}!Root Finding@{Root Finding}}
\subsubsection{\texorpdfstring{newton()}{newton()}\hspace{0.1cm}{\footnotesize\ttfamily [3/3]}}
{\footnotesize\ttfamily template$<$typename Function\+And\+Derivative , typename T $>$ \\
constexpr auto numpp\+::roots\+::newton (\begin{DoxyParamCaption}\item[{Function\+And\+Derivative \&\&}]{f,  }\item[{T \&\&}]{value,  }\item[{std\+::size\+\_\+t}]{iterations = {\ttfamily 1000},  }\item[{const double}]{epsilon = {\ttfamily 1e-\/7} }\end{DoxyParamCaption})}

A\+U\+T\+O\+M\+A\+T\+IC D\+I\+F\+F\+E\+R\+E\+N\+T\+I\+A\+T\+I\+ON O\+V\+E\+R\+L\+O\+AD

\begin{DoxyTemplParams}{Template Parameters}
{\em T} & type of function argument \\
\hline
{\em Function\+And\+Derivative} & Functor returning tuple \mbox{[}value, derivative\mbox{]} \\
\hline
{\em Derivative} & type of derivative (Functor or function)\\
\hline
\end{DoxyTemplParams}
\begin{DoxyWarning}{Warning}
Function\+And\+Derivative should be of type automatic differentiation forward
\end{DoxyWarning}
\begin{DoxySeeAlso}{See also}
\hyperlink{group__numpp__differentiation__automatic}{Automatic Differentiation}
\end{DoxySeeAlso}


\section{New Results from Relativistic Theory}
    To compute the relativistic version of the normal form factor, we
    need to use the Dirac four component spinors. As for the non
    relativistic case we need to determine the electronic charge
    density given by:
    \(
        \rho(\mb{r}) = \psi^{\dagger} \psi =
            = |\psi_1|^2 + |\psi_2|^2 + |\psi_3|^2 + |\psi_4|^2
    \)

    Using the ground state solution to the Dirac equation for hydrogenic
    atoms given by equation~\ref{eq:dirac-ground}, the electron density
    is given by:
    \begin{eqnarray*}
        \rho(\mb{r}) &=&  |g_0(r) Y_{00}|^2 +
                            \frac{1}{3} |i h_0(r) Y_{10}|^2 +
                            \frac{2}{3} |i h_0(r) Y_{11}|^2
       \\
       \rho(\mb{r}) &=&  \frac{1}{4\pi} \left( |g_0(r)|^2 +
                            |h_0(r) \cos \theta|^2  +
                            |h_0(r) \sin \theta \; e^{i\phi}|^2  \right)
       % \\
       % \rho(\mb{r}) &=&
       = \frac{1}{4\pi}
                            \left(
                                |g_0(r)|^2 + |h_0(r)|^2
                            \right)
    \end{eqnarray*}

    The radial function $g_0(r)$ and $h_0(r)$ are defined by
    equation~\ref{eq:dirac-radial}. Once again
    using the assumption that a hydrogenic atom is spherically symmetric we
    substitute the electron density $\rho$ into the normal form factor equation
    given by~\ref{eq:nff-spherical}.
    \begin{eqnarray*}
        f_0(q) &=&  \frac{1}{q}
                    \int_0^\infty \sin (qr) r
                    \left(
                        |g_0(r)|^2 + |h_0(r)|^2
                    \right) \; dr
                = \frac{2}{q(1 + \epsilon_1)}
                    \int_0^\infty r |g_0(r)|^2 \sin (qr) \; dr
        \\
                &=& \frac{1}{q \; \Gamma(2\gamma_1 + 1)}
                    \left(
                        \frac{2Z}{a_0}
                    \right)^{2\gamma_1 + 1}
                    \int_0^\infty r^{2\gamma_1 - 1} e^{-2Zr/a_0} \sin (qr) \; dr
        \\
                &=& \frac{1}{2iq \Gamma(2\gamma_1 + 1)}
                    \left(
                        \frac{2Z}{a_0}
                    \right)^{2\gamma_1 + 1}
                    \left[
                        \int_0^\infty r^{2\gamma_1-1} e^{-(2Z/a_0 - iq)r} \; dr
                    -
                        \int_0^\infty r^{2\gamma_1-1} e^{-(2Z/a_0 + iq)r} \; dr
                    \right]
    \end{eqnarray*}
    Making use of the standard integral
    \(
        \int_0^\infty x^n e^{-ax} \; dx = \frac{\Gamma(n+1)}{a^{n+1}}.
    \)
    and after some algebraic manipulation, we obtain
    equation~\ref{eq:nff-relativistic}.
    Equation~\ref{eq:nff-relativistic} is a \emph{new} result, providing an explicit
    analytic solution for the relativistic normal form factor for hydrogenic
    atoms.
    \begin{equation} \label{eq:nff-relativistic}
        \boxed{
            f_0(q) =
            \frac{\Gamma(2\gamma_1)}{2iq \Gamma(2\gamma_1+1)}
            \left(
                \frac{2Z}{a_0}
            \right)^{2\gamma_1 + 1}
            \left[
                \frac{
                    \left(
                        \frac{2Z}{a_0} + iq
                    \right)^{2\gamma_1}
                    -
                    \left(
                        \frac{2Z}{a_0} - iq
                    \right)^{2\gamma_1}
                } {
                    \left[
                        \left(
                            \frac{2Z}{a_0}
                        \right)^2
                        + q^2
                    \right]^{2\gamma_1}
                }
            \right]
        }
    \end{equation}
    This equation cannot be simplified any further because $\gamma_1$ is not an
    integer. Although the equation has expression containing the complex number
    $i$, when it is evaluated $f_0(q)$ is real valued as expected.

    Previous work in this area include the analytic atomic form factor
    for two electrons in the ground state (K shell) for a helium like atom by
    Bethe and Levinger~\cite{Bethe-Levinger} and Smend and
    Schumacher~\cite{Smend-Schumacher}. The normal form factor for two electrons in the
    K shell as quote in Schaupp et al.~\cite{Schaupp-1983} is
    \begin{equation}
        f_0(q) = \frac{(2Z\alpha)^{2\gamma_1 + 1}}{\gamma_1 q}
                \frac{ \sin[2\gamma_1 \arctan(\frac{q}{2Z\alpha}) ] }{
                    [(2Z\alpha)^2 + q^2]^{\gamma_1}
                }.
    \end{equation}


\documentclass[12pt]{mpllatex}
\usepackage{examples}

\begin{document}

\section*{Quadratic convergence of Newton-Raphson iterations}

This is a simple example that uses Maple to demonstrate the quadratic converegnce of Newton-Raphson iterations to the exact root of a non-linear equation.

\vspace{-5pt}

\begin{minipage}[t]{0.55\textwidth}
\begin{maple}
   # mplBeg (table)

      Digits := 200:

       f := x -> x - exp(-x):
      df := x -> eval (diff (f(u),u), u=x):

      x_new := 0.5:
      f_new := f (x_new):

      Print (sprintf("\\RuleA % 2d &% .25f &% .10e &\\\\",
                     0,x_new,f_new)):

      for n from 1 to 6 do
         x_old := x_new:
         x_new := x_old - f(x_old)/df(x_old):
         f_old := evalf (f (x_old)):
         f_new := evalf (f (x_new)):
         ratio := evalf (f_new / f_old^2):
         Print (sprintf("\\RuleA % 2d &% .25f &% .10e &% .5f\\\\",
                        n,x_new,f_new,ratio)):
      end do:

   # mplEnd (table)
\end{maple}
\end{minipage}
\hskip 1cm
\begin{minipage}[t]{0.45\textwidth}
\begin{latex}
   \def\eps{\epsilon}
   \def\RuleA{\vrule depth0pt  width0pt height14pt}
   \def\RuleB{\vrule depth8pt  width0pt height14pt}
   \def\RuleC{\vrule depth10pt width0pt height16pt}

   \setlength{\tabcolsep}{0.025\textwidth}%

   \begin{center}
   \begin{tabular}{cccc}%
      \noalign{\hrule height 1pt}
      \multicolumn{4}{c}{\RuleC\rmfamily\bfseries%
      Newton-Raphson iterations \quad%
      $x_{n+1} = x_n - f_n/f'_n\ ,\quad f(x) = x-e^{-x}$}\\
      \noalign{\hrule height 1pt}
      \RuleB$n$&$x_n$&
            $\eps_{n} = x_{n} - e^{-x_{n}}$&
            $\eps_{n}/\eps_{n-1}^2$\\
      \noalign{\hrule height 0.5pt}
      \mpl{table}
      \noalign{\hrule height 1pt}
   \end{tabular}
   \end{center}
\end{latex}
\end{minipage}

\clearpage

Note the clear quadratic convergence in the iterations -- the last column settles to approximately $-0.11546$ independent of the number of iterations. This behaviour would not be seen using normal floating point computations as they are normally limited to no more than 18 decimal digits. This computation used 200 decimal digits.

\def\eps{\epsilon}
\def\RuleA{\vrule depth0pt  width0pt height14pt}
\def\RuleB{\vrule depth8pt  width0pt height14pt}
\def\RuleC{\vrule depth10pt width0pt height16pt}

\setlength{\tabcolsep}{0.025\textwidth}%

\begin{center}
\begin{tabular}{cccc}%
   \noalign{\hrule height 1pt}
   \multicolumn{4}{c}{\RuleC\rmfamily\bfseries%
   Newton-Raphson iterations \quad%
   $x_{n+1} = x_n - f_n/f'_n\ ,\quad f(x) = x-e^{-x}$}\\
   \noalign{\hrule height 1pt}
   \RuleB$ n$&$ x_n$&$ \eps_{n} =  x_{n} - e^{-x_{n}}$&$\eps_{n}/\eps_{n-1}^2$\\
   \noalign{\hrule height 0.5pt}
   \mpl{table}
   \noalign{\hrule height 1pt}
\end{tabular}
\end{center}

\end{document}


\documentclass{book}

\usepackage{HBSuerDemir}
\usepackage{graphicx}
\graphicspath{ {image/} }

\begin{document}

	\paragraph{}$M_{ox} =
	\begin{cases}	\int_{a}^{b} \  f(x) \ \delta{x} \ \sqrt{1 + f^{'^{2}}(x)}\hDif {x} \\ \int_{c}^{d} \  y \ \delta{y} \ \sqrt{1 + g^{'^{2}}(y)}\hDif {y}, \\ \end{cases}$ \\
	\paragraph{}$M_{oy} = \begin{cases} \int_{a}^{b} \ x \ \delta{x} \ \sqrt{1 + f^{'^{2}}(x)}\hDif {x} \\ \int_{c}^{d} \ g(y) \ \delta{y} \ \sqrt{1 + g^{'^{2}}(y)}\hDif {y}. \\
	\end{cases}$
	\paragraph{}We define the \textit{center of mass (center of gravity)} of the arc with mass as the point G($\overline{x}$, $\overline{y}$) such that the moments m$\overline{y}$, m$\overline{x}$ of the particle G(m) are the same as the moments $M_{ox}$, $M_{oy}$ of the arc where m is the total mass of the arc:
	\begin{align*}
		m \overline{x} &= M_{oy} \ ,  &m\overline{y}= M_{ox}
	\end{align*}
	These defined equalities give
	\begin{align*}
		  \overline{x} &= \frac{M_{oy}}{m}  \text{,}   &\overline{y} = \frac{M_{ox}}{m}
	\end{align*}
	as coordinates of the center of mass G.
	\paragraph{}$\underline{Example}$. Find the center of mass of a wire bent in the shape of semi circle $x^{2}$ + $y^{2}$ = $a^{2}$ if the density is $\delta{}$ = 2y. \paragraph{}$\underline{Solution}$. Since the arc and the density function are symmetric with respect to y-axis, it follows that G lies on y, axis, and $\overline{x}$ = 0.
	\paragraph{}To find $\overline{y}$, we evaluate first the total mass m of the wire:\\
	\begin{minipage}{0.55\textwidth}
	\begin{align*}
	    m = 2\int_{0}^{a} 2y\sqrt{1 + \frac{y^2}{x^2}} \ \hDif{y} = 4a^2
	\end{align*}
	Then
	\end{minipage}
	\begin{minipage}{0.45\textwidth}
	\includegraphics[width=\textwidth]{image}
	\end{minipage}

\end{document}


\chapter{Classical Logic}

    \begin{definition*}[Formulae]
        A \textit{formula} within classical logic is constructed as follows:
        \begin{align*}
            A, B, C                \quad &\defeq \quad \top \,|\, \bot \,|\, a \,|\, \neg\, a \,|\, A \vee B \,|\, A \wedge B \\
            \Gamma, \Delta, \Sigma \quad &\defeq \quad A \,|\, A,B \,|\, A,B,C \ldots
        \end{align*}
        where $\vee, \wedge$ are additive linear logic disjunction and conjunction respectively and $\Gamma, \Delta, \Sigma$ are contexts.
    \end{definition*}

    \begin{example*}
        Consider the formulae constructed as follows:
        \begin{equation*}
            A \seteq a \vee b \quad B \seteq \neg b \vee c \quad C \seteq A \wedge B \equiv (a \vee b) \wedge (\neg b \vee c)
        \end{equation*}
    \end{example*}

    \begin{definition*}[Sequent Proofs]
        Within \textit{classical logic}, a \textit{sequent proof} is constructed from the following rules:

        \begin{minipage}[H]{\linewidth}
            \centering
            \begin{minipage}[H]{.3\linewidth}
                \begin{prooftree}
                    \AxiomC{~}
                    \RightLabel{$\top$}
                    \UnaryInfC{$\vdash \top$}
                \end{prooftree}
                \begin{prooftree}
                    \AxiomC{~}
                    \RightLabel{$ax$}
                    \UnaryInfC{$\vdash a, \neg\, a$}
                \end{prooftree}
            \end{minipage}
            \begin{minipage}[H]{.3\linewidth}
                \begin{prooftree}
                    \AxiomC{$\vdash \Gamma, A$}
                    \RightLabel{$\vee$}
                    \UnaryInfC{$\vdash \Gamma, A \vee B$}
                \end{prooftree}
                \begin{prooftree}
                    \AxiomC{$\vdash \Gamma, A$}
                    \AxiomC{$\vdash \Gamma, B$}
                    \RightLabel{$\wedge$}
                    \BinaryInfC{$\vdash \Gamma, A \wedge B$}
                \end{prooftree}
            \end{minipage}
            \begin{minipage}[H]{.3\linewidth}
                \begin{prooftree}
                    \AxiomC{$\vdash \Gamma$}
                    \RightLabel{$w$}
                    \UnaryInfC{$\vdash \Gamma, A$}
                \end{prooftree}
                \begin{prooftree}
                    \AxiomC{$\vdash \Gamma, A, A$}
                    \RightLabel{$c$}
                    \UnaryInfC{$\vdash \Gamma, A$}
                \end{prooftree}
            \end{minipage}
        \end{minipage}

        where $A, B, C$ are formulae and $\Gamma, \Delta, \Sigma$ are sequents.
        A sequent proof provides, without context, a proof of its conclusion and each line of the proof represents a tautology.
    \end{definition*}

    \begin{example*}
        Consider the formula $P \seteq (a \vee \neg a) \wedge \top$.
        The sequent proof of $P$, written $\vdash P$, is constructed as follows:
        \begin{prooftree}
            \AxiomC{$~$}
            \RightLabel{$ax$}\UnaryInfC{$\vdash a, \neg a$}
            \RightLabel{$\vee R$}\UnaryInfC{$\vdash a \vee \neg a, \neg a$}
            \RightLabel{$\vee R$}\UnaryInfC{$\vdash a \vee \neg a, a \vee \neg a$}
            \RightLabel{$c$}\UnaryInfC{$\vdash a \vee \neg a$}
            \AxiomC{$~$}
            \RightLabel{$\top$}\UnaryInfC{$\vdash \top$}
            \RightLabel{$\wedge R$}\BinaryInfC{$\vdash (a \vee \neg a) \wedge \top$}
        \end{prooftree}
    \end{example*}

    \begin{remark*}
        Within the context of weakening and contraction, \textit{additive} and \textit{multiplicative} rules of linear logic are inter-derivable.
        In this case, the \textit{additive} rules are used, with the effect of $\vee R, \wedge R$ maintaining the number of formulae in a seqent across derivation steps.
    \end{remark*}

    \begin{definition*}[Derivations]
        Given \textit{tops} $\Gamma_1 \ldots \Gamma_n$ for the sequent proof $\vdash \Delta$, a \textit{derivation} is a tree providing a proof of $\Gamma_1 \ldots \Gamma_n \implies \Delta$.

        A derivation is written as:
        \begin{prooftree}
            \AxiomC{$\vdash \Gamma_1$}
            \AxiomC{$\ldots$}
            \AxiomC{$\vdash \Gamma_n$}
            \RightLabel{\textit{[label]}} \doubleLine\TrinaryInfC{$\vdash \Delta$}
        \end{prooftree}
        where the \textit{label} describes which rules may be used within the derivation.
    \end{definition*}

    \begin{corollary*}[Derivation Equivalence]
        A sequent proof is a derivation where all top derivations of the tree are $=\joinrel= \top, ax$.
        Equivalence of derivations may be weakly defined up to equivalence of leaves and conclusion.

        This is described in detail by \citet{proofs-and-types} as \textit{morally equivalent}.
    \end{corollary*}

    \begin{example*}
        Considering the leaves $\vdash A, A$ and $\vdash B$ with the conclusion $\vdash A \wedge B$, the following proofs are morally equivalent:
        \begin{prooftree}
            \AxiomC{$\vdash A, A$}
            \RightLabel{$c$}\UnaryInfC{$\vdash A$}
            \AxiomC{$\vdash B$}
            \RightLabel{$\wedge$}\BinaryInfC{$\vdash A \wedge B$}
        \end{prooftree}
        \begin{prooftree}
            \AxiomC{$\vdash A, A$}
            \AxiomC{$\vdash B$}
            \RightLabel{$w$}\UnaryInfC{$\vdash A, B$}
            \RightLabel{$\wedge$}\BinaryInfC{$\vdash A, A \wedge B$}
            \AxiomC{$\vdash B$}
            \RightLabel{$w$}\UnaryInfC{$\vdash B, A \wedge B$}
            \RightLabel{$\wedge$}\BinaryInfC{$\vdash A \wedge B, A \wedge B$}
            \RightLabel{$c$}\UnaryInfC{$\vdash A \wedge B$}
        \end{prooftree}
        Note that the collection of leaves is a \texttt{Set}, so equivalence is up to existence of terms only and not number.
        Furthermore, equivalence of leaves is also defined up to equivalence of sequents, in particular equivalence up to commutativity of formulae $\vdash A, B \equiv \,\, \vdash B, A$.
        Equivalence may also be considered up to idempotency of formulae $\vdash A, A \equiv \,\, \vdash A$, but this interferes with the correctness of some definitions.
    \end{example*}

    \begin{definition*}[Additive Stratification]
        A proof tree is said to be \textit{additively stratified} if $\vdash P$ is structured as follows:
        \begin{prooftree}
            \AxiomC{}
            \RightLabel{$\top, ax$}\doubleLine\UnaryInfC{$\vdash A_1$}
            \RightLabel{$w$}\doubleLine\UnaryInfC{$\vdash \Gamma_1$}
            \AxiomC{\ldots}
            \AxiomC{}
            \RightLabel{$\top, ax$}\doubleLine\UnaryInfC{$\vdash A_n$}
            \RightLabel{$w$}\doubleLine\UnaryInfC{$\vdash \Gamma_n$}
            \RightLabel{$\wedge, \vee$}\doubleLine\TrinaryInfC{$\vdash P \ldots P$}
            \RightLabel{$c$}\doubleLine\UnaryInfC{$\vdash P$}
        \end{prooftree}
        That is, the inferences made in an additively stratified proof are strictly ordered by:
        \begin{enumerate}[nosep]
            \item Top/Axiomatic
            \item Weakening
            \item Conjunction/Disjunction
            \item Contraction
        \end{enumerate}
    \end{definition*}

    \begin{example}\label{example:add-strat-proof}
        The following proof tree is additively stratified:
        \begin{prooftree}
            \AxiomC{}
            \RightLabel{$ax$}\UnaryInfC{$\vdash a, \neg a$}
            \RightLabel{$\vee$}\UnaryInfC{$\vdash a \vee \neg a, \neg a$}
            \RightLabel{$\vee$}\UnaryInfC{$\vdash a \vee \neg a, a \vee \neg a$}
            \AxiomC{}
            \RightLabel{$\top$}\UnaryInfC{$\vdash \top$}
            \RightLabel{$w$}\UnaryInfC{$\vdash \top, a \vee \neg a$}
            \RightLabel{$\wedge$}\BinaryInfC{$\vdash (a \vee \neg a) \wedge \top, a \vee \neg a$}
            \AxiomC{}
            \RightLabel{$\top$}\UnaryInfC{$\vdash \top$}
            \RightLabel{$w$}\UnaryInfC{$\vdash \top, (a \vee \neg a) \wedge \top$}
            \RightLabel{$\wedge$}\BinaryInfC{$\vdash (a \vee \neg a) \wedge \top, (a \vee \neg a) \wedge \top$}
            \RightLabel{$c$}\UnaryInfC{$\vdash (a \vee \neg a) \wedge \top$}
        \end{prooftree}
    \end{example}

    \begin{proposition*}[Stratification Equivalence]
        Given $\vdash A$, there exists a morally equivalent additively stratified proof of $A$.
    \end{proposition*}

    \begin{proof}
        For each instance of a weakening below another inference, there exists an equivalent subproof that is additively stratified:

        \begin{minipage}[H]{\linewidth}
            \centering
            \begin{minipage}[H]{0.4\linewidth}
                \begin{prooftree}
                    \AxiomC{$\vdash \Gamma, A$}
                    \RightLabel{$\vee$}\UnaryInfC{$\vdash \Gamma, A \vee B$}
                    \RightLabel{$w$}\UnaryInfC{$\vdash \Gamma, A \vee B$, C}
                \end{prooftree}
            \end{minipage}
            $\leadsto$
            \begin{minipage}[H]{0.4\linewidth}
                \begin{prooftree}
                    \AxiomC{$\vdash \Gamma, A$}
                    \RightLabel{$w$}\UnaryInfC{$\vdash \Gamma, A, C$}
                    \RightLabel{$\vee$}\UnaryInfC{$\vdash \Gamma, A \vee B, C$}
                \end{prooftree}
            \end{minipage}
        \end{minipage}

        \begin{minipage}[H]{\linewidth}
            \centering
            \begin{minipage}[H]{0.4\linewidth}
                \begin{prooftree}
                    \AxiomC{$\vdash \Gamma, A$}
                    \AxiomC{$\vdash \Gamma, B$}
                    \RightLabel{$\wedge$}\BinaryInfC{$\vdash \Gamma, A \wedge B$}
                    \RightLabel{$w$}\UnaryInfC{$\vdash \Gamma, A \wedge B, C$}
                \end{prooftree}
            \end{minipage}
            $\leadsto\quad$
            \begin{minipage}[H]{0.4\linewidth}
                \begin{prooftree}
                    \AxiomC{$\vdash \Gamma, A$}
                    \RightLabel{$w$}\UnaryInfC{$\vdash \Gamma, A, C$}
                    \AxiomC{$\vdash \Gamma, B$}
                    \RightLabel{$w$}\UnaryInfC{$\vdash \Gamma, B, C$}
                    \RightLabel{$\wedge$}\BinaryInfC{$\vdash \Gamma, A \wedge B, C$}
                \end{prooftree}
            \end{minipage}
        \end{minipage}

        \begin{minipage}[H]{\linewidth}
            \centering
            \begin{minipage}[H]{0.4\linewidth}
                \begin{prooftree}
                    \AxiomC{$\vdash \Gamma, A, A$}
                    \RightLabel{$c$}\UnaryInfC{$\vdash \Gamma, A$}
                    \RightLabel{$w$}\UnaryInfC{$\vdash \Gamma, A, B$}
                \end{prooftree}
            \end{minipage}
            $\leadsto\quad$
            \begin{minipage}[H]{0.4\linewidth}
                \begin{prooftree}
                    \AxiomC{$\vdash \Gamma, A, A$}
                    \RightLabel{$w$}\UnaryInfC{$\vdash \Gamma, A, A, B$}
                    \RightLabel{$c$}\UnaryInfC{$\vdash \Gamma, A, B$}
                \end{prooftree}
            \end{minipage}
        \end{minipage}

        Similarly, for each instance of a contraction above another inference, there exists an equivalent subproof that is additively stratified:

        \begin{minipage}[H]{\linewidth}
            \centering
            \begin{minipage}[H]{0.4\linewidth}
                \begin{prooftree}
                    \AxiomC{$\vdash \Gamma, A, A$}
                    \RightLabel{$c$}\UnaryInfC{$\vdash \Gamma, A$}
                    \RightLabel{$\vee$}\UnaryInfC{$\vdash \Gamma, A \vee B$}
                \end{prooftree}
            \end{minipage}
            $\leadsto$
            \begin{minipage}[H]{0.4\linewidth}
                \begin{prooftree}
                    \AxiomC{$\vdash \Gamma, A, A$}
                    \RightLabel{$\vee$}\UnaryInfC{$\vdash \Gamma, A \vee B, A$}
                    \RightLabel{$\vee$}\UnaryInfC{$\vdash \Gamma, A \vee B, A \vee B$}
                    \RightLabel{$c$}\UnaryInfC{$\vdash \Gamma, A \vee B$}
                \end{prooftree}
            \end{minipage}
        \end{minipage}

        \begin{minipage}[H]{\linewidth}
            \centering
            \begin{minipage}[H]{0.3\linewidth}
                \begin{scprooftree}{0.8}
                    \AxiomC{$\vdash \Gamma, A, A$}
                    \RightLabel{$c$}\UnaryInfC{$\vdash \Gamma, A$}
                    \AxiomC{$\vdash \Gamma, B$}
                    \RightLabel{$\wedge$}\BinaryInfC{$\vdash \Gamma, A \wedge B$}
                \end{scprooftree}
            \end{minipage}
            $\leadsto\quad$
            \begin{minipage}[H]{0.6\linewidth}
                \begin{scprooftree}{0.8}
                    \AxiomC{$\vdash \Gamma, A, A$}
                    \AxiomC{$\vdash \Gamma, B$}
                    \RightLabel{$w$}\UnaryInfC{$\vdash \Gamma, A, B$}
                    \RightLabel{$\wedge$}\BinaryInfC{$\vdash \Gamma, A, A \wedge B$}
                    \AxiomC{$\vdash \Gamma, B$}
                    \RightLabel{$w$}\UnaryInfC{$\vdash \Gamma, B, A \wedge B$}
                    \RightLabel{$\wedge$}\BinaryInfC{$\vdash \Gamma, A \wedge B, A \wedge B$}
                    \RightLabel{$c$}\UnaryInfC{$\vdash \Gamma, A \wedge B$}
                \end{scprooftree}
            \end{minipage}
        \end{minipage}

        By induction from the leaves downwards on a finite height tree, apply the associated rule to each pair of inferences of the form ($c$ above \textit{inf}).
        Any given $\vdash P$ may be rewritten:
        \begin{prooftree}
            \AxiomC{}
            \RightLabel{$\top, ax$}\doubleLine\UnaryInfC{$\vdash A_1$}
            \RightLabel{$\wedge, \vee, w$}\doubleLine\UnaryInfC{$\vdash \Gamma_1$}
            \AxiomC{\ldots}
            \AxiomC{}
            \RightLabel{$\top, ax$}\doubleLine\UnaryInfC{$\vdash A_n$}
            \RightLabel{$\wedge, \vee, w$}\doubleLine\UnaryInfC{$\vdash \Gamma_n$}
            \RightLabel{$c$}\doubleLine\TrinaryInfC{$\vdash P$}
        \end{prooftree}

        Again, by induction from the root upwards on this partially stratified tree, apply the associated rule to each pair of inferences of the form ($w$ below \textit{inf}).
        $\vdash P$ may then be further rewritten:
        \begin{prooftree}
            \AxiomC{}
            \RightLabel{$\top, ax$}\doubleLine\UnaryInfC{$\vdash A_1$}
            \RightLabel{$w$}\doubleLine\UnaryInfC{$\vdash \Gamma_1$}
            \AxiomC{\ldots}
            \AxiomC{}
            \RightLabel{$\top, ax$}\doubleLine\UnaryInfC{$\vdash A_n$}
            \RightLabel{$w$}\doubleLine\UnaryInfC{$\vdash \Gamma_n$}
            \RightLabel{$\wedge, \vee$}\doubleLine\TrinaryInfC{$\vdash P \ldots P$}
            \RightLabel{$c$}\doubleLine\UnaryInfC{$\vdash P$}
        \end{prooftree}

    \end{proof}

    \begin{example*}
        Similarly to Example~\ref{example:add-strat-proof}, consider the two following morally equivalent proofs, with only the latter additively stratified.
        \begin{prooftree}
            \AxiomC{}
            \RightLabel{$ax$}\UnaryInfC{$\vdash a, \neg a$}
            \RightLabel{$\vee$}\UnaryInfC{$\vdash a \vee \neg a, \neg a$}
            \RightLabel{$\vee$}\UnaryInfC{$\vdash a \vee \neg a, a \vee \neg a$}
            \RightLabel{$w$}\UnaryInfC{$\vdash a \vee \neg a$}
            \AxiomC{}
            \RightLabel{$\top$}\UnaryInfC{$\vdash \top$}
            \RightLabel{$\wedge$}\BinaryInfC{$\vdash (a \vee \neg a) \wedge \top$}
        \end{prooftree}
        \begin{prooftree}
            \AxiomC{}
            \RightLabel{$ax$}\UnaryInfC{$\vdash a, \neg a$}
            \RightLabel{$\vee$}\UnaryInfC{$\vdash a \vee \neg a, \neg a$}
            \RightLabel{$\vee$}\UnaryInfC{$\vdash a \vee \neg a, a \vee \neg a$}
            \AxiomC{}
            \RightLabel{$\top$}\UnaryInfC{$\vdash \top$}
            \RightLabel{$w$}\UnaryInfC{$\vdash \top, a \vee \neg a$}
            \RightLabel{$\wedge$}\BinaryInfC{$\vdash (a \vee \neg a) \wedge \top, a \vee \neg a$}
            \AxiomC{}
            \RightLabel{$\top$}\UnaryInfC{$\vdash \top$}
            \RightLabel{$w$}\UnaryInfC{$\vdash \top, (a \vee \neg a) \wedge \top$}
            \RightLabel{$\wedge$}\BinaryInfC{$\vdash (a \vee \neg a) \wedge \top, (a \vee \neg a) \wedge \top$}
            \RightLabel{$c$}\UnaryInfC{$\vdash (a \vee \neg a) \wedge \top$}
        \end{prooftree}
        Note that moral equivalence here is without regard to number --- there are two leaves $\vdash \top$ under additive stratification versus one otherwise.
        Furthermore, notice that the proof without additive stratification is shorter --- this will be of importance when improving asymptotic performance.
    \end{example*}


\chapter{Propositional Logic}
\begin{definition}
    A \underline{\textbf{proposition}} is a statement with exactly one truth
    value.
\end{definition}
\begin{definition}
    Two propositions are said to be \underline{\textbf{equivalent}} if they
    have the same truth table.
\end{definition}
\begin{definition}
    A \underline{\textbf{tautology}} is a statement that is always true.
\end{definition}
\begin{definition}
    A \underline{\textbf{contradiction}} is a statement that is always false.
\end{definition}

\section{Truth Tables and Logical Equivalences}
If you are given a proposition and asked to check if it is a tautology or a
contradiction, here are two different ways to proceed:

\begin{enumerate}[noitemsep]
    \item Construct a truth table for the given proposition.
    \item Use logical equivalences.
\end{enumerate}

\begin{question}
    Is this a tautology or a contradiction?

    \[
        [p \wedge (q \wedge r)] \rightarrow [( ( (r \wedge p)\wedge q) \vee q)]
    \]
\end{question}

\begin{solution}
    \textbf{1 - Truth Table:} For readability, let us define $\alpha =  p
    \wedge (q \wedge r)$ and let us define $\beta = ( ( (r \wedge p)\wedge q)
    \vee q)$

    \pagebreak[4]

    \begin{table}[ht]
        \caption{Truth Table}
        \vspace{0.5em}
        \centering % used for centering table
        \begin{tabular}{c c c c c c c c c } % 9 columns
        % centered columns (4 columns)
            \toprule
            p & q & r & $q \wedge r$ &  $\alpha$ & $(r \wedge p)$ & $((r \wedge
            p) \wedge q)$ & $\beta$ & $\alpha \rightarrow \beta$\\ [0.5ex]
            \midrule
            T & T & T & T & T & T & T & T & \textbf{T} \\
            T & T & F & F & F & F & F & T & \textbf{T} \\
            T & F & T & F & F & T & F & F & \textbf{T} \\
            T & F & F & F & F & F & F & F & \textbf{T} \\
            F & T & T & T & F & F & F & T & \textbf{T} \\
            F & T & F & F & F & F & F & T & \textbf{T} \\
            F & F & T & F & F & F & F & F & \textbf{T} \\
            F & F & F & F & F & F & F & F & \textbf{T} \\
            \bottomrule
        \end{tabular}
        \label{table:question_1_truthtable}
    \end{table}

    \noindent Since $\alpha \rightarrow \beta$ is always true, this is an example
    of a tautology!
\end{solution}

\begin{solution}
    \textbf{2 - Logical Equivalences: }
    \[
        \begin{split}
            &[p \wedge (q \wedge r)] \rightarrow [( ( (r \wedge p)\wedge q) \vee
            q)] \\
            \iff &\neg[p \wedge q \wedge r] \vee [(  (r \wedge p\wedge q) \vee q)]
            \textbf{ (Definition)} \\
            \iff &\neg (p \wedge q \wedge r) \vee [(p \wedge q \wedge r) \vee q]
            \textbf{ (Commutative law)} \\
            \iff &[\neg (p \wedge q \wedge r) \vee (p \wedge q \wedge r)] \vee
            q \textbf{ (Associative Law)} \\
            \iff &T \vee q \textbf{ (Complement Law)} \\
            \iff &T (\textbf{Identity Law}) \\
        \end{split}
    \]
    \noindent Since the result is always true, the given proposition is a
    tautology! \\
\end{solution}

\begin{remark}
    As you can see, solving problems through logical equivalences is quicker,
    but require you to manipulate the given propositions. If you are
    uncomfortable doing this, please feel free to resort to Truth Tables. The
    same question showed up on my midterm, and I used logical equivalences to
    solve the problem.
\end{remark}

\section{Knights and Knaves}
You can always expect a question on logic puzzles on the midterms and the
finals. These questions are actually fun to do and are not too difficult.

You will be given a situation and you are required to use truth tables to solve
the problem. Here is a sample problem (From a past midterm):

A very special island is inhabited only by Knights and Knaves. Knights always
tell the truth,while Knaves always lie. You meet three inhabitants: Alex, John
and Sally.Alex says, “John is a Knight if and only if Sally is a Knave”. John
says, “If Sally is a Knight, then Alex is a Knight”.

\begin{question}
    Can you find what Alex, John, and Sally are? Explain your answer.
\end{question}

\begin{solution}
    Let us break down the problem:

    You have three people: Alex (A), John (J), and Sally (S). Each of them are
    either a Knight or a Knave. Hence, we have 8 possible rows in our truth table.

    Let us also break down what the people have to say:

    \begin{enumerate}
        \item Alex says, ``John is a Knight if and only if Sally is a Knave,"
            which basically means: \textbf{John is a Knight} $\iff$
            \textbf{Sally is a Knave.}
        \item John says, ``If Sally is a Knight, then Alex is a Knight," which
            basically means: \textbf{Sally is a Knight} $\implies$ \textbf{Alex
            is a Knight.}
    \end{enumerate}

    With this information, let us construct our truth table:

    \begin{table}[ht]
        \caption{Truth Table}
        \centering
        \begin{tabular}{c c c c c c}
            \toprule
            A & J & S & Alex Says & John Says & Does This Work?\\ [0.5ex]
            \midrule
            Knight & Knight & Knight & F & T & \textbf{No} - Alex is a Knight who is
            lying\\
            Knight & Knight & Knave & T & T & \textbf{YES}\\
            Knight & Knave & Knight & T & T & \textbf{No} - John is a Knave who is telling
            the truth\\
            Knight & Knave & Knave & F & T & \textbf{No} -John is a Knave who is telling
            the truth\\
            Knave & Knight & Knight & F & F & \textbf{No} - John is a Knight who is lying\\
            Knave & Knight & Knave & T & T & \textbf{No} - Alex is a Knave who is telling
            the truth\\
            Knave & Knave & Knight & T & F & \textbf{No} - Alex is a Knave who is telling
            the truth \\
            Knave & Knave & Knave & F & T & \textbf{No} - John is a Knave who is telling
            the truth\\
            \bottomrule
        \end{tabular}
        \label{table:nonlin} % is used to refer this table in the text
    \end{table}
    \noindent From this, we can see that there is only one possible
    combination, that Alex and John are Knights and Sally is a Knave. \\ \\
\end{solution}

\begin{remark}
    Sometimes there may be more than one possible combination that works out,
    in that case it is not possible to correctly determine who is who, but it
    is one of those correct combinations.
\end{remark}

\begin{remark}
    There's almost always a Knights and Knaves (or a variation) question on the
    exams.
\end{remark}

\begin{remark}
    If you are interested in these problems, These problems are called
    \emph{Smullyan's Island Puzzles}.
\end{remark}

\section{Additional Exercises}
Please note that there are no solutions for the following questions.

\subsection{Logic}
\begin{question}
    Construct the truth table for the following proposition:

    \[
        [p \wedge (p \rightarrow q)] \rightarrow q
    \]

    This rule of inference is commonly referred to as \emph{Modus Ponens}.
\end{question}

\begin{question}
    Prove or disprove:

    \[
        (p \rightarrow q) \Leftrightarrow (q \rightarrow p)
    \]
\end{question}

\begin{question}
    Is this a tautology or a contradiction?

    \[
        (( (P \rightarrow Q) \wedge (R \rightarrow S) \wedge (P \vee R))) \rightarrow
        (Q \vee S)
    \]

    You may use either Truth Tables or Logical Equivalences for this question.

    This proposition is usually referred to as the \emph{Constructive
    Dilemma}.
\end{question}

\begin{question}
    Prove or disprove:

    \[
        (p \oplus q) \Leftrightarrow (p \wedge \neg q) \vee (\neg p \wedge q)
    \]
\end{question}

\subsection{Logic Puzzles}
%1) You meet two inhabitants, Alex and John, in an island of %Knights and
%Knaves. You also know that Knights always tell %the truth and Knaves always
%lie. Alex tells you, "At least %one of us is a Knave". Again, Alex tells you,
%"Both of us are %Knaves". What can you conclude from the given information? \\
%\\

\begin{question}
    A very special island is inhabited only by Knights and Knaves. Knights
    always tell the truth, while Knaves always lie. You meet three inhabitants:
    Alex, John and Sally. Alex says, "John is a Knight, if and only if Sally is
    a Knave". John says, "If Sally is a Knight, then Alex is a Knight". What
    can you conclude from the given information?
\end{question}

\begin{question}
    A very special island is inhabited only by knights and knaves. Knights
    always tell the truth, and knaves always lie. You meet three inhabitants:
    Alex, John and Sally. Alex says, "At least one of the following is true:
    that Sally is a knave or that I am a knight." John says, "Alex could claim
    that I am a knave." Sally claims, "Neither Alex nor John are knights." What
    can you conclude from the given information?
\end{question}