%
% %CopyrightBegin%
%
% Copyright Ericsson AB 2017. All Rights Reserved.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% %CopyrightEnd%
%

\chapter{Arithmetics}

\label{chapter:arithmetics}

\emph{We define the mathematical functions in terms of which the arithmetics of
\Erlang\ are defined.  This chapter depends significantly on the international
standard document ISO/IEC 10967-1 \cite{lia-1}, referenced in this
text as LIA-1\index{LIA-1}.}

\ifStd
\emph{This chapter also contains the information needed for a
LIA-1 language binding for \StdErlang.}
\fi

\section{Notation}

\label{section:notation-arith}

Let $\INTS$\index{Z@$\INTS$ (the integers)} be the set of mathematical integers,
$\REALS$\index{R@$\REALS$ (the reals)} the set of
real numbers and $\BOOLEANS$\index{B@$\BOOLEANS$ (the Booleans)} the set of Booleans, denoted by
\B{true}\index{true@\B{true}}
and \B{false}\index{false@\B{false}}.

There are four exceptional values\index{arithmetic!exceptional values}
that are not numbers but may be the
results of the LIA-1 functions defined in this chapter:
\B{integer\_overflow}\index{integer_overflow@\B{integer\_overflow}},
\B{floating\_overflow}\index{floating_overflow@\B{floating\_overflow}},
\B{underflow}\index{underflow@\B{underflow}} and
\B{undefined}\index{undefined@\B{undefined}}.

\ifStd
An implementation conforming to IEC 559\index{IEC 559} \cite{iec559} has three additional values
that are not numbers but may appear as input to floating-point arithmetic operations
and can be returned from such operations:
\B{not_a_number}\index{not_a_number@\B{not_a_number}},
\B{positive_infinity}\index{positive_infinity@\B{positive_infinity}}
and \B{negative_infinity}\index{negative_infinity@\B{negative_infinity}}.
\fi

The following definitions are restated from LIA-1\index{LIA-1}.
For $x\in\REALS$, the notation $\lfloor x\rfloor$ stands for the largest integer not greater than $x$:
\[\lfloor x\rfloor\in\INTS\text{\quad and\quad}x-1<\lfloor x\rfloor\leq x\]
and $\mathit{tr}(x)$ stands for the integer part of $x$ (truncated towards 0):
\begin{alignat*}{2}
\mathit{tr}(x) &= \lfloor x\rfloor && \qquad\text{if $x\geq0$;} \\
               &= -\lfloor-x\rfloor && \qquad\text{if $x<0$.}
\end{alignat*}

The following definitions are restated from the 1995 working draft of
the international standard document ISO/IEC 10967-2 \cite{lia-2},
referenced in this text as LIA-2\index{LIA-2}.

Let $S$ be a subset of $\REALS$, closed under (arithmetic) negation.
The following are four rounding functions\index{rounding function}
for mapping values of $\REALS$ into $S$.
\index{  floor@$\lfloor\cdot\rfloor_S$|(}
\index{  ceiling@$\lceil\cdot\rceil_S$|(}
\index{floor@$\mathit{floor}_S$|(}
\index{ceiling@$\mathit{ceiling}_S$|(}
\index{truncate@$\mathit{truncate}_S$|(}
\index{nearest@$\mathit{nearest}_S$|(}
Given any $x\in\REALS$,
\begin{alignat*}{2}
\lfloor x\rfloor_S &= \max \{\,z\in S \mid z \leq x\,\} \displaybreak[0]\\[\smallskipamount]
\lceil x\rceil_S &= \min \{\,z\in S \mid z \geq x\,\} \displaybreak[0]\\[\smallskipamount]
\mathit{truncate}_S(x) &= \lfloor x\rfloor_S && \qquad\text{if $x\geq0$;} \\
                       &= \lceil x\rceil_S && \qquad\text{if $x<0$.} \displaybreak[0]\\[\smallskipamount]
\mathit{nearest}_S(x) &= \lfloor x\rfloor_S && \qquad\text{if $|\lfloor x\rfloor_S - x| < |x - \lceil x\rceil_S|$;} \\
                      &= \lceil x\rceil_S && \qquad\text{if $|\lfloor x\rfloor_S - x| > |x - \lceil x\rceil_S|$;} \\
                      &= \text{$\lfloor x\rfloor_S$ or $\lceil x\rceil_S$} && \qquad\text{if $|\lfloor x\rfloor_S - x| = |x - \lceil x\rceil_S|$.}
\end{alignat*}
In addition it must hold that $\mathit{nearest}_S(-x)=-\mathit{nearest}_S(x)$.

When the subscript $S$ is omitted, $\INTS$ is assumed.

We may write $\mathit{floor}_S(x)$ for $\lfloor x\rfloor_S$ and
$\mathit{ceiling}_S(x)$ for $\lceil x\rceil_S$.

Note that
\begin{itemize}
\item $\mathit{floor}_S(x)$ rounds $x$ towards negative infinity,
\item $\mathit{ceiling}_S(x)$ rounds $x$ towards positive infinity,
\item $\mathit{truncate}_S(x)$ rounds $x$ towards zero and
\item $\mathit{nearest}_S(x)$ rounds $x$ to the nearest value in $S$.
\end{itemize}
\index{  floor@$\lfloor\cdot\rfloor_S$|)}
\index{  ceiling@$\lceil\cdot\rceil_S$|)}
\index{floor@$\mathit{floor}_S$|)}
\index{ceiling@$\mathit{ceiling}_S$|)}
\index{truncate@$\mathit{truncate}_S$|)}
\index{nearest@$\mathit{nearest}_S$|)}
When we write $[i,j]$\index{ interval closed@$[\cdot,\cdot]$},
where $i$ and $j$ are integers, we mean the
set $\{\,x\in\INTS \mid i\leq x\leq j\,\}$.
When we write $[i,j)$\index{ interval open@$[\cdot,\cdot)$},
where $i$ and $j$ are integers, we mean the
set $\{\,x\in\INTS \mid i\leq x< j\,\}$.

\section{The integer type}

\label{section:integer-type}
\index{integer!properties|(}

\ifStd
A \StdErlang\ implementation must provide at least one integer type that
conforms with LIA-1.  In this document that type is assumed to be the
only integer type.
\fi
\index{I@$I$|(}
The set of numbers that can be represented by the integer type is
called $I$ and is a subset of $\INTS$\index{Z@$\INTS$ (the integers)}.
LIA-1 requires $I$ to be characterized by four parameters:
\index{bounded@\I{bounded}|(}
\index{modulo@\I{modulo}|(}
\index{minint@\I{minint}|(}
\index{maxint@\I{maxint}|(}
\begin{textdisplay}
\begin{tabular}{@{}ll@{}}
$\I{bounded}\in\BOOLEANS$ & (whether the set $I$ is finite) \\
$\I{modulo}\in\BOOLEANS$ & (whether out-of-bounds results ``wrap'') \\
$\I{minint}\in I$ & (the smallest integer in $I$) \\
$\I{maxint}\in I$ & (the largest integer in $I$)
\end{tabular}
\end{textdisplay}
\ifStd
For the integer type of a \StdErlang\ implementation it is required
that \I{modulo} is \B{false}, while \I{bounded} may be either \B{true}
or \B{false}.
\begin{itemize}
\item If \I{bounded} is \B{false}, then $I=\INTS$ and the values of \I{minint} and
\I{maxint} are not meaningful.
\item If \I{bounded} is \B{true}, then
$I = \{\,x \in \INTS \mid \I{minint} \leq x \leq \I{maxint}\,\}$
where
$\I{maxint} \geq 2^{59}-1$ and either
$\I{minint} = -(\I{maxint}+1)$ or $\I{minint} = -\I{maxint}$.
\end{itemize}
\fi
\ifOld
For the integer type of \Erlang, \I{modulo} and \I{bounded} are \B{false}.
As \I{bounded} is \B{false}, $I=\INTS$ and the values of \I{minint} and
\I{maxint} are not meaningful.
\fi
\index{bounded@\I{bounded}|)}
\index{modulo@\I{modulo}|)}
\index{minint@\I{minint}|)}
\index{maxint@\I{maxint}|)}
\Erlang\ has three additional parameters:
\index{fixnum@\I{fixnum}|(}
\index{minfixnum@\I{minfixnum}|(}
\index{maxfixnum@\I{maxfixnum}|(}
\begin{textdisplay}
\begin{tabular}{@{}ll@{}}
$\I{fixnum}\in\BOOLEANS$ & (whether there are ``fixnums'') \\
$\I{minfixnum}\in I$ & (the smallest fixnum in $I$) \\
$\I{maxfixnum}\in I$ & (the largest fixnum in $I$)
\end{tabular}
\end{textdisplay}
\ifStd
If \I{fixnum} is \B{true}, then it must hold that
\[\I{minint} \leq \I{minfixnum} \leq \I{maxfixnum} \leq \I{maxint}.\]
\fi
\ifOld
\I{fixnum} is \B{true}, \I{minfixnum} is $-2^{27}$ and
\I{maxfixnum} is $2^{27}-1$.
\fi
\index{I@$I$|)}

\index{integer!fixnum|(}
\index{I f@$I_f$|(}
\ifStd If \I{fixnum} is \B{true}, let \fi
\ifOld Let \fi
$I_f = \{\,x\in I \mid \I{minfixnum} \leq x \leq \I{maxfixnum}\,\}$.
\ifStd
Otherwise, let $I_f = \emptyset$.
\fi
$I_f$ is
\ifStd meant to be \fi
the set of ``fixnums'', the representation of which can utilize the
most efficient representation of integers in the machine, typically occupying
one word of memory.
\index{I f@$I_f$|)}
\ifStd
The values of \I{minfixnum} and \I{maxfixnum} for an implementation in which
\I{fixnum} is \B{true} should be chosen
so that when both the operands and the result of an integer addition,
subtraction, multiplication or division are in $I_f$, it should be
possible to utilize the most efficient machine instructions for
computing the operation.  Typically one would expect $\I{minfixnum} =
-(\I{maxfixnum}+1)$ but this is not required. For example, an
implementation may have ``unsigned'' fixnums in which case
\I{minfixnum} and \I{maxfixnum} could be $0$ and $2^{28}-1$,
respectively.
\fi
\index{integer!fixnum|)}
\index{fixnum@\I{fixnum}|)}
\index{minfixnum@\I{minfixnum}|)}
\index{maxfixnum@\I{maxfixnum}|)}

\index{integer!bignum|(}
Let $I_b = I \setminus I_f$\index{I b@$I_b$}.
$I_b$ is the set of ``bignums'', the representation of which
may require arbitrary amounts of memory.
An implementation for which $I_b\neq\emptyset$
\ifOld, such as \Erlang,\fi\ is said to have bignums.
\index{integer!bignum|)}

\ifStd
As the parameter \I{modulo} is always \B{false} for the integer type,
it is not made available to programs.  The other parameters are
available through the BIFs
\T{integer:bounded/0}, \T{integer:min_fixnum/0},
\T{integer:max_fix\-num/0},
\T{integer:min_int/0} and
\T{integer:max_int/0} (\S\ref{section:integer-module}).
\fi
\index{integer!properties|)}

\section{Integer operations}

\label{section:integer-operations}
\index{integer!arithmetic operations|(}

Elsewhere in this specification we express the integer arithmetic
operations of \Erlang\ in terms of the following functions from LIA-1:
\begin{xxalignat}{2}
&\lefteqn{\mathit{add}_I : I\times I\to I\cup\{\B{integer\_overflow}\}} \\
&&&(x,y)\mapsto\text{the sum of $x$ and $y$} \displaybreak[0]\\[\smallskipamount]
&\lefteqn{\mathit{sub}_I : I\times I\to I\cup\{\B{integer\_overflow}\}} \\
&&& (x,y)\mapsto\text{the difference of $x$ and $y$} \displaybreak[0]\\[\smallskipamount]
&\lefteqn{\mathit{mul}_I : I\times I\to I\cup\{\B{integer\_overflow}\}} \\
&&& (x,y)\mapsto\text{the product of $x$ and $y$} \displaybreak[0]\\[\smallskipamount]
&\lefteqn{\mathit{div}_I : I\times I\to I\cup\{\B{integer\_overflow},\B{undefined}\}} \\
&&& (x,y)\mapsto\text{the quotient of $x$ and $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{rem}_I : I\times I\to I\cup\{\B{undefined}\} && (x,y)\mapsto\text{the remainder of $x$ and $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{mod}_I : I\times I\to I\cup\{\B{undefined}\} && (x,y)\mapsto\text{$x$ modulo $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{neg}_I : I\to I\cup\{\B{integer\_overflow}\} && (x)\mapsto\text{the (arithmetic) negation of $x$} \displaybreak[0]\\[\smallskipamount]
&\mathit{abs}_I : I\to I\cup\{\B{integer\_overflow}\} && (x)\mapsto\text{absolute value of $x$} \displaybreak[0]\\[\smallskipamount]
\ifStd
&\mathit{sign}_I : I\to I  && (x)\mapsto\text{the sign of $x$} \displaybreak[0]\\[\smallskipamount]
\fi
&\mathit{eq}_I : I\times I\to\BOOLEANS  && (x,y)\mapsto\text{$x$ equals $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{neq}_I : I\times I\to\BOOLEANS && (x,y)\mapsto\text{$x$ does not equal $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{lss}_I : I\times I\to\BOOLEANS && (x,y)\mapsto\text{$x$ is less than $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{leq}_I : I\times I\to\BOOLEANS && (x,y)\mapsto\text{$x$ is not greater than $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{gtr}_I : I\times I\to\BOOLEANS && (x,y)\mapsto\text{$x$ is greater than $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{geq}_I : I\times I\to\BOOLEANS && (x,y)\mapsto\text{$x$ is not less than $y$}
\end{xxalignat}
For each function, LIA-1 states a number of axioms.
\ifStd
A \StdErlang\ implementation must satisfy all of these with the added
restriction that $\mathit{modulo}=\B{false}$\index{modulo@\I{modulo}}
(\S\ref{section:integer-type}),
\index{minint@\I{minint}|(}
\index{maxint@\I{maxint}|(}
either $\mathit{minint}=-\mathit{maxint}$ or $\mathit{minint}=-(\mathit{maxint}+1)$
(when $\mathit{bounded}=\B{true}$\index{bounded@\I{bounded}}),
\index{minint@\I{minint}|)}
\index{maxint@\I{maxint}|)} and
$\mathit{mod}_I=\mathit{mod}_I^a$.
\StdErlang\ provides operators for both the pairs $\mathit{div}_I^f/\mathit{rem}_I^f$ and
$\mathit{div}_I^t/\mathit{rem}_I^t$.
\fi
\ifOld
In \OldErlang, $\mathit{modulo}=\B{false}$\index{modulo@\I{modulo}} (\S\ref{section:integer-type}),
$\mathit{bounded}=\B{false}$\index{bounded@\I{bounded}} and $\mathit{mod}_I=\mathit{mod}_I^a$.
For $\mathit{div}$ and $\mathit{rem}$ the pair $\mathit{div}_I^t/\mathit{rem}_I^t$ is provided.
\fi

For convenience we reproduce the
strengthened axioms of Section~5.1.3 of LIA-1 here:
\begin{alignat*}{2}
\mathit{add}_I(x,y) &= x+y && \qquad\text{if $x+y\in I$;} \\
                    &= \B{integer\_overflow} && \qquad\text{if $x+y\notin I$.} \displaybreak[0]\\[\smallskipamount]
\mathit{sub}_I(x,y) &= x-y && \qquad\text{if $x-y\in I$;} \\
                    &= \B{integer\_overflow} && \qquad\text{if $x-y\notin I$.} \displaybreak[0]\\[\smallskipamount]
\mathit{mul}_I(x,y) &= x*y && \qquad\text{if $x*y\in I$;} \\
                    &= \B{integer\_overflow} && \qquad\text{if $x*y\notin I$.} \displaybreak[0]\\[\smallskipamount]
\mathit{div}_I^f(x,y) &= \lfloor x/y\rfloor && \qquad\text{if $y\neq0$ and $\lfloor x/y\rfloor\in I$;} \\
                    &= \B{integer\_overflow} && \qquad\text{if $y\neq0$ and $\lfloor x/y\rfloor\notin I$;} \\
                    &= \B{undefined} && \qquad\text{if $y=0$.} \displaybreak[0]\\[\smallskipamount]
\mathit{rem}_I^f(x,y) &= x-(\lfloor x/y\rfloor*y) && \qquad\text{if $y\neq0$;} \\
                    &= \B{undefined} && \qquad\text{if $y=0$.} \displaybreak[0]\\[\smallskipamount]
\mathit{div}_I^t(x,y) &= \mathit{tr}(x/y) && \qquad\text{if $y\neq0$ and $\mathit{tr}(x/y)\in I$;} \\
                    &= \B{integer\_overflow} && \qquad\text{if $y\neq0$ and $\mathit{tr}(x/y)\notin I$;} \\
                    &= \B{undefined} && \qquad\text{if $y=0$.} \displaybreak[0]\\[\smallskipamount]
\mathit{rem}_I^t(x,y) &= x-(\mathit{tr}(x/y)*y) && \qquad\text{if $y\neq0$;} \\
                    &= \B{undefined} && \qquad\text{if $y=0$.} \displaybreak[0]\\[\smallskipamount]
\mathit{mod}_I^a(x,y) &= x-(\lfloor x/y\rfloor*y) && \qquad\text{if $y\neq0$;} \\
                    &= \B{undefined} && \qquad\text{if $y=0$.} \displaybreak[0]\\[\smallskipamount]
\mathit{neg}_I(x)   &= -x && \qquad\text{if $-x\in I$;} \\
                    &= \B{integer\_overflow} && \qquad\text{if $-x\notin I$.} \displaybreak[0]\\[\smallskipamount]
\mathit{abs}_I(x)   &= |x| && \qquad\text{if $|x|\in I$;} \\
                    &= \B{integer\_overflow} && \qquad\text{if $|x|\notin I$.} \displaybreak[0]\\[\smallskipamount]
\ifStd
\mathit{sign}_I(x)  &= 1 && \qquad\text{if $x>0$;} \\
                    &= 0 && \qquad\text{if $x=0$;} \\
                    &= -1 && \qquad\text{if $x<0$.} \displaybreak[0]\\[\smallskipamount]
\fi
\mathit{eq}_I(x,y)  &= \B{true} && \qquad\text{if $x=y$;} \\
                    &= \B{false} && \qquad\text{if $x\neq y$.} \displaybreak[0]\\[\smallskipamount]
\mathit{neq}_I(x,y) &= \B{true} && \qquad\text{if $x\neq y$;} \\
                    &= \B{false} && \qquad\text{if $x=y$.} \displaybreak[0]\\[\smallskipamount]
\mathit{lss}_I(x,y) &= \B{true} && \qquad\text{if $x<y$;} \\
                    &= \B{false} && \qquad\text{if $x\geq y$.} \displaybreak[0]\\[\smallskipamount]
\mathit{leq}_I(x,y) &= \B{true} && \qquad\text{if $x\leq y$;} \\
                    &= \B{false} && \qquad\text{if $x>y$.} \displaybreak[0]\\[\smallskipamount]
\mathit{gtr}_I(x,y) &= \B{true} && \qquad\text{if $x>y$;} \\
                    &= \B{false} && \qquad\text{if $x\leq y$.} \displaybreak[0]\\[\smallskipamount]
\mathit{geq}_I(x,y) &= \B{true} && \qquad\text{if $x\geq y$;} \\
                    &= \B{false} && \qquad\text{if $x<y$.}
\end{alignat*}

\iffalse
When these functions are used in other chapters, it will sometimes be
convenient to write applications of them to \Erlang\ integer terms,
rather than to the integers that these terms denote.  Similarly we
will sometimes use the result of one of the mathematical functions as
if it were an \Erlang\ integer term.
\fi
\index{integer!arithmetic operations|)}

\section{The floating-point type}

\label{section:float-type}
\index{float!properties|(}

\ifStd
A \StdErlang\ implementation must provide at least one floating-point
type that conforms with LIA-1.  In this document that type is assumed
to be the only floating-point type.
\fi
\index{F@$F$|(}
The set of numbers that can be
represented by the float type is called $F$ and is a finite subset of
$\REALS$\index{R@$\REALS$ (the reals)}.  $F$ may contain both
normalized and denormalized values (cf.~Section~5.2 of LIA-1);
$F_N$ stands for the set of normalized values in $F$.

LIA-1 requires $F$ to be characterized by five parameters:
\index{r@$r$|(}
\index{p@$p$|(}
\index{emin@$\mathit{emin}$|(}
\index{emax@$\mathit{emax}$|(}
\index{denorm@$\mathit{denorm}$|(}
\begin{textdisplay}
\begin{tabular}{@{}ll@{}}
$p\in\INTS$ & (the precision of $F$) \\
$r\in\INTS$ & (the radix of $F$) \\
$\I{emin}\in\INTS$ & (the smallest exponent of $F$) \\
$\I{emax}\in\INTS$ & (the largest exponent of $F$) \\
$\I{denorm}\in\BOOLEANS$ & (whether $F$ contains denormalized values)
\end{tabular}
\end{textdisplay}

\ifOld
\OldErlang\ directly uses the float representation of the underlying
processor so these parameters are not defined.  It is guaranteed,
however, that the size of a float is at least 64 bits.
\iffalse
$r$ is $2$,
$p$ is XXX,
$\mathit{emin}$ is XXX,
$\mathit{emax}$ is XXX and
$\mathit{denorm}$ is \B{true}.
\fi\fi

\ifStd
These parameters are available through the BIFs
\T{float:precision/0}, \T{float:radix/0},
\T{float:e_min/0},
\T{float:e_max/0} and \T{float:de\-norm/0}, respectively (\S\ref{section:float-module}).

In addition to the requirements of Section~5.2 of LIA-1, the following must
hold for the floating-point type of a \StdErlang\ implementation
(from Section~A.5.2.0.2 of LIA-1):
\begin{itemize}
\item $r$ should be even,
\item $r^{p-1}\geq 10^6$,
\item $\I{emin}-1 \leq k*(p-1)$ with $k\geq 2$ and $k$ as large an integer as practical,
\item $\I{emax} > k*(p-1)$, and
\item $-2 \leq (emin-1) + emax \leq 2$.
\end{itemize}

\index{r@$r$|)}
\index{p@$p$|)}
\index{emin@$\mathit{emin}$|)}
\index{emax@$\mathit{emax}$|)}
\index{denorm@$\mathit{denorm}$|)}

The range and granularity of $F$ are characterized by four derived
constants:
\index{fmax@$\mathit{fmax}$|(}
\index{fmin@$\mathit{fmin}$|(}
\index{fminN@$\mathit{fmin}_N$|(}
\index{epsilon@$\mathit{epsilon}$|(}
\begin{textdisplay}
\begin{tabular}{@{}ll@{}}
$\mathit{fmax}\in F$ & (the value of largest magnitude in $F$) \\
$\mathit{fmin}\in F$ & (the value of smallest magnitude in $F$) \\
$\mathit{fmin}_N\in F$ & (the smallest normalized value in $F$) \\
$\mathit{epsilon}\in F$ & (the largest relative representation error in $F_N$)
\end{tabular}
\end{textdisplay}
\index{fmax@$\mathit{fmax}$|)}
\index{fmin@$\mathit{fmin}$|)}
\index{fminN@$\mathit{fmin}_N$|)}
\index{epsilon@$\mathit{epsilon}$|)}
\index{F@$F$|)}

\iffalse
\ifOld
For \OldErlang,
$\mathit{fmax}$ is XXX,
$\mathit{fmin}$ is XXX,
$\mathit{fmin}_N$ is XXX and
$\mathit{epsilon}$ is XXX.
\fi\fi

These derived constants are available through the BIFs
\T{float:f_max/0}, \T{float:f_min/0},
\T{float:f_min_norm/0} and
\T{float:epsilon/0}, respectively (\S\ref{section:float-module}).
\fi
\index{float!properties|)}

\section{Floating-point operations}

\label{section:float-operations}
\index{float!arithmetic operations|(}

Elsewhere in this specification we express the floating-point
arithmetic operations of \Erlang\ in terms of the following functions
from LIA-1:
\begin{xxalignat}{2}
&\lefteqn{\mathit{add}_F : F\times F\to F\cup\{\B{floating\_overflow},\B{underflow}\}} \\
 &&& (x,y)\mapsto\text{the sum of $x$ and $y$} \displaybreak[0]\\[\smallskipamount]
&\lefteqn{\mathit{sub}_F : F\times F\to F\cup\{\B{floating\_overflow},\B{underflow}\}} \\
 &&& (x,y)\mapsto\text{the difference of $x$ and $y$} \displaybreak[0]\\[\smallskipamount]
&\lefteqn{\mathit{mul}_F : F\times F\to F\cup\{\B{floating\_overflow},\B{underflow}\}} \\
 &&& (x,y)\mapsto\text{the product of $x$ and $y$} \displaybreak[0]\\[\smallskipamount]
&\lefteqn{\mathit{div}_F : F\times F\to F\cup\{\B{floating\_overflow},\B{underflow},\B{undefined}\}} \\
 &&& (x,y)\mapsto\text{the quotient of $x$ and $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{neg}_F : F\to F && (x)\mapsto\text{the (arithmetic) negation of $x$} \displaybreak[0]\\[\smallskipamount]
&\mathit{abs}_F : F\to F && (x)\mapsto\text{absolute value of $x$} \displaybreak[0]\\[\smallskipamount]
&\mathit{sign}_F : F\to I && (x)\mapsto\text{the sign of $x$}\displaybreak[0]\\[\smallskipamount]
&\lefteqn{\mathit{exponent}_F : F\to F\cup\{\B{undefined}\}} \\
 &&& (x)\mapsto\text{the exponent of $x$} \displaybreak[0]\\[\smallskipamount]
&\mathit{fraction}_F : F\to F && (x)\mapsto\text{$x$ scaled by a power of $r$ to the range $[1/r,1)$} \displaybreak[0]\\[\smallskipamount]
&\lefteqn{\mathit{scale}_F : F\times I\times F\to F\cup\{\B{floating\_overflow},\B{underflow}\}} \\
 &&& (x,n)\mapsto\text{the product of $x$ and $r^n$} \displaybreak[0]\\[\smallskipamount]
&\lefteqn{\mathit{succ}_F : F\to F\cup\{\B{floating\_overflow}\}} \\
 &&& (x)\mapsto\text{the least float greater than $x$} \displaybreak[0]\\[\smallskipamount]
&\lefteqn{\mathit{pred}_F : F\to F\cup\{\B{floating\_overflow}\}} \\
 &&& (x)\mapsto\text{the greatest float less than $x$} \displaybreak[0]\\[\smallskipamount]
&\lefteqn{\mathit{ulp}_F : F\to F\cup\{\B{underflow},\B{undefined}\}} \\
 &&& (x)\mapsto\text{the value of one unit in the last place of $x$} \displaybreak[0]\\[\smallskipamount]
&\mathit{trunc}_F : F\times I\to F && (x)\mapsto\text{$x$ with the low $p-n$ digits zeroed} \displaybreak[0]\\[\smallskipamount]
&\lefteqn{\mathit{round}_F : F\times I\to F\cup\{\B{floating\_overflow}\}} \\
 &&& (x)\mapsto\text{$x$ rounded to $n$ significant digits} \displaybreak[0]\\[\smallskipamount]
&\mathit{intpart}_F : F\to F && (x)\mapsto\text{the integer part of $x$} \displaybreak[0]\\[\smallskipamount]
&\mathit{fractpart}_F : F\to F && (x)\mapsto\text{$x$ minus the integer part of $x$} \displaybreak[0]\\[\smallskipamount]
&\mathit{eq}_F : F\times F\to\BOOLEANS && (x,y)\mapsto\text{$x$ equals $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{neq}_F : F\times F\to\BOOLEANS && (x,y)\mapsto\text{$x$ does not equal $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{lss}_F : F\times F\to\BOOLEANS && (x,y)\mapsto\text{$x$ is less than $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{leq}_F : F\times F\to\BOOLEANS && (x,y)\mapsto\text{$x$ is not greater than $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{gtr}_F : F\times F\to\BOOLEANS && (x,y)\mapsto\text{$x$ is greater than $y$} \displaybreak[0]\\[\smallskipamount]
&\mathit{geq}_F : F\times F\to\BOOLEANS && (x,y)\mapsto\text{$x$ is not less than $y$}
\end{xxalignat}
\ifStd
(LIA-1 specifies that the type of $\mathit{sign}_F$ should be $F\to F$ but in \Erlang\
the resulting integer can be automatically coerced to a float and an integer is more
useful than a float for dispatching upon.)
\fi
For each function, LIA-1 states a number of axioms.
\ifStd A \StdErlang\ implementation must satisfy all of these axioms. \fi
For convenience we reproduce the axioms of Section~5.2.7 of LIA-1 here:
\begin{alignat*}{2}
\mathit{add}_F(x,y) &= \mathit{result}_F(\mathit{add}_F^*(x+y),\mathit{rnd}_F) && \displaybreak[0]\\[\smallskipamount]
\mathit{sub}_F(x,y) &= \mathit{add}_F(x,-y) && \displaybreak[0]\\[\smallskipamount]
\mathit{mul}_F(x,y) &= \mathit{result}_F(x*y,\mathit{rnd}_F) && \displaybreak[0]\\[\smallskipamount]
\mathit{div}_F(x,y) &= \mathit{result}_F(x/y,\mathit{rnd}_F) && \qquad\text{if $y\neq0$;} \\
                    &= \B{undefined} && \qquad\text{if $y=0$.} \displaybreak[0]\\[\smallskipamount]
\mathit{neg}_F(x)   &= -x &&  \displaybreak[0]\\[\smallskipamount]
\mathit{abs}_F(x)   &= |x| && \displaybreak[0]\\[\smallskipamount]
\mathit{sign}_F(x)  &= 1 && \qquad\text{if $x>0$;} \\
                    &= 0 && \qquad\text{if $x=0$;} \\
                    &= -1 && \qquad\text{if $x<0$.} \displaybreak[0]\\[\smallskipamount]
\mathit{exponent}_F(x) &= \lfloor(\log_r|x|\rfloor+1 && \qquad\text{if $x\neq0$;} \\
                    &= \B{undefined} && \qquad\text{if $x=0$.} \displaybreak[0]\\[\smallskipamount]
\mathit{fraction}_F(x) &= x/r^{\mathit{exponent}_F(x)} && \qquad\text{if $x\neq0$;} \\
                    &= \B{undefined} && \qquad\text{if $x=0$.} \displaybreak[0]\\[\smallskipamount]
\mathit{scale}_F(x,n) &= \mathit{result}_F(x*r^n,\mathit{rnd}_F) && \displaybreak[0]\\[\smallskipamount]
\mathit{succ}_F(x)  &= \min\{\,z\in F \mid z > x\,\} && \qquad\text{if $x\neq\mathit{fmax}$;} \\
                    &= \B{floating\_overflow} && \qquad\text{if $x=\mathit{fmax}$.} \displaybreak[0]\\[\smallskipamount]
\mathit{pred}_F(x)  &= \max\{\,z\in F \mid z < x\,\} && \qquad\text{if $x\neq-\mathit{fmax}$;} \\
                    &= \B{floating\_overflow} && \qquad\text{if $x=-\mathit{fmax}$.} \displaybreak[0]\\[\smallskipamount]
\mathit{ulp}_F(x)   &= r^{e_F(x)-p} && \qquad\text{if $x\neq0$ and $r^{e_F(x)-p}\in F$;} \\
                    &= \B{underflow} && \qquad\text{if $x\neq0$ and $r^{e_F(x)-p}\notin F$;} \\
                    &= \B{undefined} && \qquad\text{if $x=0$.} \displaybreak[0]\\[\smallskipamount]
\mathit{trunc}_F(x) &= \lfloor x/r^{e_F(x)-n}\rfloor*r^{e_F(x)-n} && \qquad\text{if $x\geq0$;} \\
                    &= -\mathit{trunc}_F(-x,n) && \qquad\text{if $x<0$.} \displaybreak[0]\\[\smallskipamount]
\mathit{round}_F(x) &= \mathit{rn}_F(x,n) && \qquad\text{if $|\mathit{rn}_F(x,n)|\leq\mathit{fmax}$;} \\
                    &= \B{floating\_overflow} && \qquad\text{if $|\mathit{rn}_F(x,n)|>\mathit{fmax}$.} \displaybreak[0]\\[\smallskipamount]
\mathit{intpart}_F(x) &= \mathit{sign}_F(x)*\lfloor|x|\rfloor && \displaybreak[0]\\[\smallskipamount]
\mathit{fractpart}_F(x) &= x-\mathit{intpart}_F(x) && \displaybreak[0]\\[\smallskipamount]
\mathit{eq}_F(x,y)  &= \B{true} && \qquad\text{if $x=y$;} \\
                    &= \B{false} && \qquad\text{if $x\neq y$.} \displaybreak[0]\\[\smallskipamount]
\mathit{neq}_F(x,y) &= \B{true} && \qquad\text{if $x\neq y$;} \\
                    &= \B{false} && \qquad\text{if $x=y$.} \displaybreak[0]\\[\smallskipamount]
\mathit{lss}_F(x,y) &= \B{true} && \qquad\text{if $x<y$;} \\
                    &= \B{false} && \qquad\text{if $x\geq y$.} \displaybreak[0]\\[\smallskipamount]
\mathit{leq}_F(x,y) &= \B{true} && \qquad\text{if $x\leq y$;} \\
                    &= \B{false} && \qquad\text{if $x>y$.} \displaybreak[0]\\[\smallskipamount]
\mathit{gtr}_F(x,y) &= \B{true} && \qquad\text{if $x>y$;} \\
                    &= \B{false} && \qquad\text{if $x\leq y$.} \displaybreak[0]\\[\smallskipamount]
\mathit{geq}_F(x,y) &= \B{true} && \qquad\text{if $x\geq y$;} \\
                    &= \B{false} && \qquad\text{if $x<y$.}
\end{alignat*}
The functions are expressed in terms of a number of helper functions and sets:
\begin{itemize}
\item The set $F^*$\index{F*@$F^*$} is $F$ extended with all numbers having the same precision as numbers
in $F_N$ but larger magnitude.
\item The approximate addition function $\mathit{add}_F^* : F\times F\to\REALS$ is as
described in Section~5.2.4 of LIA-1, ideally but not necessarily such that
$\mathit{add}_F^*(x,y)=x+y$.
\item The functions $e_F : \REALS\to\INTS$ and $\mathit{rn}_F : F\times\INTS\to F^*$
are as described in Section~5.2.7 of LIA-1, i.e., they are defined such that
\begin{alignat*}{2}
e_F(x) &= \lfloor\log_r|x|\rfloor+1 && \qquad\text{if $|x|\geq\mathit{fmin}_N$;} \\
       &= \mathit{emin} && \qquad\text{if $|x|<\mathit{fmin}_N$.} \displaybreak[0]
\end{alignat*}
and
\[\mathit{rn}_F(x,n) = \mathit{sign}_F(x)*\lfloor|x|/r^{e_F(x)-n}+1/2\rfloor*r^{e_F(x)-n}\]
\item $\mathit{rnd}_F : \REALS\to F^*$ is the rounding function\index{rounding function}
used when taking an exact
result in $\REALS$ to a $p$-digit approximation.  It must satisfy the requirements
stated in Sections~5.2.5 and~5.2.8 of LIA-1.  There are two derived constants characterizing
$\mathit{rnd}_F$:
\begin{itemize}
\item $\I{rnd\_error}\in\REALS$ is the maximum rounding error in ulps;
\item $\I{rnd\_style}\in\{\B{nearest},\B{truncate},\B{other}\}$ is the rounding style.
\end{itemize}
\ifOld
For \OldErlang, $\mathit{rnd\_error}$ is XXX and $\mathit{rnd\_style}$
is XXX.
\fi
\ifStd
They are available at run time through the BIFs
\T{float:rnd_error/0} and
\T{float:rnd_style/0} (\S\ref{section:float-module}).
\fi
\item $\mathit{result}_F : \REALS\times(\REALS\to F^*)\to
F\cup\{\B{floating\_overflow},\B{underflow}\}$ is the function described in Section~5.2.6
of LIA-1.  The value of $\mathit{result}_F(x,\mathit{rnd})$, where $x\in\REALS$ and
\I{rnd} is a rounding function in $\REALS\to F^*$, is the result of applying the
rounding function to $x$, provided that the result is in $F$.
\ifStd
If $|x|$ is greater
than zero but less than \I{fmin}, $\mathit{result}_F(x,\mathit{rnd})$ can always be
\B{underflow} but may be $\mathit{rnd}(x)$ if \I{denorm} is \B{true} and no
denormalization loss occurs at $x$.
A \StdErlang\ implementation for which
\I{denorm} is \B{true} shall document how this choice is made.
\fi
\ifOld
If $|x|$ is greater
than zero but less than \I{fmin}, then XXX???
\fi
\end{itemize}
\index{float!arithmetic operations|)}

\section{Conversions}

\label{section:conversions}
\index{conversion!arithmetic|(}

\ifStd
In a \StdErlang\ implementation with more than one integer type or more
than one floating-point type, conversion functions between integer
types and between floating-point types shall be provided that satisfy
the requirements in Section~5.3 of LIA-1.
\fi

Let $\mathit{nearest}_{I\to F} : I\to F\cup\{\B{floating_overflow}\}$
be defined as
\[\mathit{nearest}_{I\to F}(x) = \mathit{result}_F(x,\mathit{nearest}_F),\]
where $\mathit{result}_F$ is as in \S\ref{section:float-operations}
(cf.~Section~5.2.6 of LIA-1) and $\mathit{nearest}_F$ is a
rounding-to-nearest function for $F$ (\S\ref{section:notation-arith}).

Define the following four functions:
\begin{alignat*}{2}
\mathit{floor}_{F\to I}(x) &= \mathit{floor}_Z(x) && \qquad\text{if $\mathit{floor}_Z(x)\in I$;} \\
       &= \B{integer\_overflow} && \qquad\text{if $\mathit{floor}_Z(x)\notin I$.} \displaybreak[0]\\[\smallskipamount]
\mathit{ceiling}_{F\to I}(x) &= \mathit{ceiling}_Z(x) && \qquad\text{if $\mathit{ceiling}_Z(x)\in I$;} \\
       &= \B{integer\_overflow} && \qquad\text{if $\mathit{ceiling}_Z(x)\notin I$.} \displaybreak[0]\\[\smallskipamount]
\mathit{truncate}_{F\to I}(x) &= \mathit{truncate}_Z(x) && \qquad\text{if $\mathit{truncate}_Z(x)\in I$;} \\
       &= \B{integer\_overflow} && \qquad\text{if $\mathit{truncate}_Z(x)\notin I$.} \displaybreak[0]\\[\smallskipamount]
\mathit{nearest}_{F\to I}(x) &= \mathit{nearest}_Z(x) && \qquad\text{if $\mathit{nearest}_Z(x)\in I$;} \\
       &= \B{integer\_overflow} && \qquad\text{if $\mathit{nearest}_Z(x)\notin I$.}
\end{alignat*}
Note that the four functions $\mathit{floor}_Z$, $\mathit{ceiling}_Z$,
$\mathit{truncate}_Z$ and $\mathit{nearest}_Z$ meet the requirements
in Section~5.3 of LIA-1 for being used as the rounding function
$\mathit{rnd}_{F\to I}$ in a conversion function $\mathit{cvt}_{F\to
I}$.
\index{conversion!arithmetic|)}

\section{Representation and evaluation}

\label{section:eval-notation}

The purpose of this section is to define notation and terminology that is
used in the subsequent chapters.

\index{Re@$\Re[\cdot]$|(}
\begin{itemize}
\item If $i\in I$, then $\Re[i]$ is the \Erlang\ integer representing $i$.
\item If $f\in F$, then $\Re[f]$ is the \Erlang\ float representing $f$.
\item If $b\in\BOOLEANS$, i.e., \B{true} or \B{false}, then $\Re[b]$
is the \Erlang\ Boolean atom representing $b$.  That is,
$\Re[\B{true}]=\T{true}$ and $\Re[\B{false}]=\T{false}$.
\item If $x$ is one of %the exceptional values
\B{integer\_overflow},
\B{floating\_overflow}, \B{underflow} and \B{undefined}, then
$\Re[x]$ is
\ifStd
the \Erlang\ atom given by Table~\ref{table:arith-exits}.
\fi
\ifOld
the \Erlang\ atom \T{badarith}.
\fi
\end{itemize}
\index{Re@$\Re[\cdot]$|)}

\ifStd
\begin{table}
\begin{center}
\index{integer_overflow@\B{integer\_overflow}|(}
\index{floating_overflow@\B{floating\_overflow}|(}
\index{underflow@\B{underflow}|(}
\index{undefined@\B{undefined}|(}
\index{integer_overflow exit signal@\T{integer\_overflow} exit signal|(}
\index{float_overflow exit signal@\T{float\_overflow} exit signal|(}
\index{float_underflow exit signal@\T{float\_underflow} exit signal|(}
\index{undefined_arith exit signal@\T{undefined_arith} exit signal|(}
\begin{tabular}{@{}ll@{}}
\hline
Exceptional value & Exit reason \\
\hline
\B{integer\_overflow} & \T{integer_overflow} \\
\B{floating\_overflow} & \T{float_overflow} \\
\B{underflow} & \T{float_underflow} \\
\B{undefined} & \T{undefined_arith} \\
\hline
\end{tabular}
\caption{Exit reasons for exceptional values\index{arithmetic!exceptional values}.}
\label{table:arith-exits}
\index{integer_overflow@\B{integer\_overflow}|)}
\index{floating_overflow@\B{floating\_overflow}|)}
\index{underflow@\B{underflow}|)}
\index{undefined@\B{undefined}|)}
\index{integer_overflow exit signal@\T{integer\_overflow} exit signal|)}
\index{float_overflow exit signal@\T{float\_overflow} exit signal|)}
\index{float_underflow exit signal@\T{float\_underflow} exit signal|)}
\index{undefined_arith exit signal@\T{undefined_arith} exit signal|)}
\end{center}
\end{table}
\fi

\index{Re-1@$\Er[\cdot]$|(}
Similarly,
\begin{itemize}
\item If \TZ{I} is an Erlang\ integer, then $\Er[\TZ{I}]\in I$ is the
integer it represents.
\item If \TZ{F} is an Erlang\ float, then $\Er[\TZ{F}]\in F$ is the
real number it represents.
\item If \TZ{B} is an Erlang\ Boolean atom, then $\Er[\TZ{B}]\in\BOOLEANS$ is the
Boolean it represents.
That is, $\Er[\T{true}]=\B{true}$ and $\Er[\T{false}]=\B{false}$.
\end{itemize}
\index{Re-1@$\Er[\cdot]$|)}

We have a notation for writing the result of evaluating an expression:
\begin{itemize}
\item When we write $\TZ{E}\RETURNS\TZ{T}$\index{  returns@$\RETURNS$}
we state that evaluating the expression
\TZ{E} completes normally and that its value is the term \TZ{T}.  (If the
environment is relevant, it is stated elsewhere.)
\item When we write $\TZ{E}\EXITSWITH\TZ{R}$\index{  exitswith@$\EXITSWITH$}
we state that evaluating the expression
\TZ{E} exits with reason \TZ{R}.
\end{itemize}

\iffalse
\label{section:arith-shorthand}

When describing the evaluation of arithmetic expressions in
\S\ref{chapter:expressions-evaluation} and the BIFs in \S\ref{chapter:bifs},
it will be convenient to use also the following shorthand.

\index{apply!arithmetic operation|(}

When we write ``apply $f_I$ to $\TZ{v}_1$'' where
$f_I$ is one of the integer operations in
\S\ref{section:integer-operations} and $\TZ{v}_1$ is an \Erlang\ term, we mean
\begin{itemize}
\item If $\TZ{v}_1$ is an \Erlang\ integer, then
\begin{itemize}
\item If $f_I(\Er[\TZ{v}_1])\in I$, then $\Re[f_I(\Er[\TZ{v}_1])]$
is the result.
\item If $f_I(\Er[\TZ{v}_1])=\B{integer\_overflow}$, then exit with \T{integer_overflow}.
\item If $f_I(\Er[\TZ{v}_1])=\B{undefined}$, then exit with \T{undefined}.
\end{itemize}
\item If $\TZ{v}_1$ is not an \Erlang\ integer, exit with \T{\badarith}.
\end{itemize}
Similarly for ``apply $f_I$ to $\TZ{v}_1$ and $\TZ{v}_2$'', where both
$\TZ{v}_1$ and $\TZ{v}_2$ must be \Erlang\ integers.

When we write ``apply $f_F$ to $\TZ{v}_1$'' where
$f_F$ is one of the floating-point operations in
\S\ref{section:float-operations} and $\TZ{v}_1$ is an \Erlang\ term, we mean
\begin{itemize}
\item If $\TZ{v}_1$ is an \Erlang\ float, then
\begin{itemize}
\item If $f_F(\Er[\TZ{v}_1])\in F$, then $\Re[f_F(\Er[\TZ{v}_1])]$
is the result.
\item If $f_F(\Er[\TZ{v}_1])=\B{floating\_overflow}$, then exit with \T{floating_overflow}.
\item If $f_F(\Er[\TZ{v}_1])=\B{undefined}$, then exit with \T{undefined}.
\end{itemize}
\item If $\TZ{v}_1$ is not an \Erlang\ float, exit with \T{\badarith}.
\end{itemize}
Similarly for ``apply $f_F$ to $\TZ{v}_1$ and $\TZ{v}_2$'', where both
$\TZ{v}_1$ and $\TZ{v}_2$ must be \Erlang\ floats.

When we write ``apply $f$ to $\TZ{v}_1$''\ where $f_I$ is one of the
integer operations in
\S\ref{section:integer-operations}, $f_F$ is one of the floating-point operations in
\S\ref{section:float-operations} and $\TZ{v}_1$ is an \Erlang\ term, we mean
\begin{itemize}
\item If $\TZ{v}_1$ is an \Erlang\ integer, then apply $f_I$ to
$\TZ{v}_1$.
\item If $\TZ{v}_1$ is an \Erlang\ float, then apply $f_F$ to
$\TZ{v}_1$.
\item Otherwise, exit with \T{badarg}.
\end{itemize}
Similarly for ``apply $f$ to $\TZ{v}_1$ and $\TZ{v}_2$'', where either both
$\TZ{v}_1$ and $\TZ{v}_2$ must be \Erlang\ integers or both must be
\Erlang\ floats.

When we write ``apply $f_{I\to F}$ to $\TZ{v}_1$''\ where
$f_{I\to F}$ is one of the integer to float conversion operations in
\S\ref{section:conversions} and $\TZ{v}_1$ is an
\Erlang\ term, we mean
\begin{itemize}
\item If $\TZ{v}_1$ is an \Erlang\ integer, then
\begin{itemize}
\item If $f_{I\to F}(\Er[\TZ{v}_1])\in F$, then $\Re[f_{I\to F}(\Er[\TZ{v}_1])]$ is the result.
\item If $f_{I\to F}(\Er[\TZ{v}_1])=\B{floating\_overflow}$, then exit with \T{floating_overflow}.
\end{itemize}
\item If $\TZ{v}_1$ is an \Erlang\ float, then $\TZ{v}_1$ is the result.
\item If $\TZ{v}_1$ is neither an \Erlang\ integer, nor a float, exit with \TZ{badarg}.
\end{itemize}

When we write ``apply $f_{F\to I}$ to $\TZ{v}_1$''\ where
$f_{F\to I}$ is one of the float to integer conversion operations in
\S\ref{section:conversions} and $\TZ{v}_1$ is an
\Erlang\ term, we mean
\begin{itemize}
\item If $\TZ{v}_1$ is an \Erlang\ float, then
\begin{itemize}
\item If $f_{F\to I}(\Er[\TZ{v}_1])\in I$, then $\Re[f_{F\to I}(\Er[\TZ{v}_1])]$ is the result.
\item If $f_{F\to I}(\Er[\TZ{v}_1])=\B{integer\_overflow}$, then exit with \T{integer_overflow}.
\end{itemize}
\item If $\TZ{v}_1$ is an \Erlang\ integer, then $\TZ{v}_1$ is the result.
\item If $\TZ{v}_1$ is neither an \Erlang\ integer, nor a float, exit with \TZ{badarg}.
\end{itemize}

The result and exit refer to the result and exit of the expression
being described or the application of the BIF being described.
\index{apply!arithmetic operation|)}
\fi % iffalse

\section{Notification}

\index{arithmetic!notification|(}

Whenever the evaluation of the translated \Erlang\ expressions causes
one of the functions defined in the preceding sections of this chapter
to return an exceptional value, the evaluation of the translated
\Erlang\ expression exits with
\ifStd
a reason that depends on the
exceptional value, cf.~Table~\ref{table:arith-exits}.
\fi
\ifOld
reason \T{badarith}.
\fi

A \ifStd\T{try} expression (\S\ref{section:try-expr}) \else
\T{catch} expression (\S\ref{section:catch}) \fi
can be used for handling
the exception in accordance with Section~6.1.1 of LIA-1.

The usual mechanisms for handling of abnormal completion ensure that
in absence of a \ifStd\T{try} \else\T{catch} \fi expression that catches the arithmetic
exception, the process will complete abruptly; any exit signals sent
to linked processes will propagate information about the arithmetic
exception (\S\ref{section:exit-signals}).

\index{arithmetic!notification|)}

\iffalse
% !!! I would like to have this one included.
\section{Translation}

\index{arithmetic!translation|(}
\emph{In this section I will tell how arithmetic expressions are expected to
be translated into combinations of LIA-1 operations.  Pretty easy since there
is only one integer and one float type.  The dynamic typing might make it
a little more messy.}
\index{arithmetic!translation|)}
\fi

\ifStd
\section{Conformity with IEC 559}

\label{section:arith-iec559}

\index{IEC 559|(}
\index{iec_559@\I{iec\_559}|(}
This specification does not specify a language binding for that part
of IEC~559 (a.\,k.\,a.\ ANSI/IEEE Std.\ 754-1985) \cite{iec559} that
is not covered by LIA-1, except that there is a parameter
$\mathit{iec\_559}\in\BOOLEANS$ that should be \B{true} in an
implementation that fully conforms to IEC~559 and \B{false} elsewhere.

The parameter $\mathit{iec\_559}$ is available to programs through the BIF \linebreak
\T{float:iec_559/0} (\S\ref{section:float:iec5590}).
\index{IEC 559|)}
\index{iec_559@\I{iec\_559}|)}
\fi

\section{Conversion to and from numerals}

We will define conversions from $I$ and $F$ to canonical decimal numerals.
Below we will only discuss decimal numerals and thus omit ``decimal''.
We will also define conversions from decimal numerals to $I$ or $F$.

\subsection{Integer to decimal numeral}

\label{section:integer-to-numeral}
\index{integer!conversion to numeral|(}
Given an integer $i\in I$, the canonical numeral is defined recursively as follows.
\begin{itemize}
\item If $0\leq i<10$, then the canonical numeral for $i$ is the decimal digit with value $i$.
\item If $i<0$, then the canonical numeral for $i$ is a minus sign (`$-$') followed by the
canonical numeral for $-i$.
\item If $i\geq10$, then the canonical numeral for $i$ is the canonical numeral
for $\lfloor i/10\rfloor$ followed by the decimal digit with value $i\bmod10$.
\end{itemize}
\index{integer!conversion to numeral|)}

\subsection{Decimal numeral to integer}

\label{section:numeral-to-integer}
\index{integer!conversion from numeral|(}
Given a sequence of characters, its interpretation as a decimal integer numeral
(if any) is defined as follows:
\begin{itemize}
\item If the sequence consists of a minus sign followed by decimal digits $d_1$, \ldots, $d_k$,
then it denotes $-i$, where $i$ is the integer denoted by the digits $d_1$, \ldots, $d_k$.
\item If the sequence consists of a plus sign followed by decimal digits $d_1$, \ldots, $d_k$,
then it denotes the same integer as that denoted by the digits $d_1$, \ldots, $d_k$.
\item If the sequence consists only of decimal digits $d_1$, \ldots, $d_k$, then it
denotes the integer $\sum_{j=1}^k d_j\cdot10^{k-j}$.
\item Otherwise, it does not denote any integer.
\end{itemize}
Note that this also defines the meaning of a
\NT{DecimalLiteral}\index{DecimalLiteral@\NT{DecimalLiteral}}:
if the sequence of characters
that it constitutes denotes $i\in I$, then the \NT{DecimalLiteral} denotes $\Re[i]$.
\index{integer!conversion from numeral|)}

\subsection{Numeral with radix to integer}

\label{section:radix-numeral-to-integer}
\index{integer!conversion from numeral|(}
In this context, `A' and `a' are digits
with value 10, `B' and `b' are digits with value 11, etc., up to `F' and `f' which are digits
with value 15.
Given a radix $r$ and a sequence of characters, its interpretation as an
integer numeral in radix $r$ (if any) is defined as follows:
\begin{itemize}
\item If the sequence consists of a minus sign followed by digits $d_1$, \ldots, $d_k$,
then it denotes $-i$, where $i$ is the integer denoted by the digits $d_1$, \ldots, $d_k$.
\item If the sequence consists of a plus sign followed by decimal digits $d_1$, \ldots, $d_k$,
then it denotes the same integer as that denoted by the digits $d_1$, \ldots, $d_k$.
\item If the sequence consists only of digits $d_1$, \ldots, $d_k$ where each digit $d_j$,
$1\leq j\leq k$, has a value that is less than $r$, then it
denotes the integer $\sum_{j=1}^k d_j\cdot r^{k-j}$.
\item Otherwise, it does not denote any integer.
\end{itemize}
Note that this also defines the meaning of a
\NT{ExplicitRadixLiteral}\index{ExplicitRadixLiteral@\NT{ExplicitRadixLiteral}}:
consider the sequence of characters that it constitutes.
Let $r$ be the integer denoted by the digits before the `\#' character.  If
the concatenation of
the sign (if any) with the digits following the `\#' character denotes
$i\in I$ in radix $r$, then the \NT{ExplicitRadixLiteral} denotes $\Re[i]$.
\index{integer!conversion from numeral|)}

\subsection{Float to numeral}

\label{section:float-to-numeral}
\index{float!conversion to numeral|(}
The canonical numeral for a float $f\in F$ is defined recursively as follows.
\begin{itemize}
\item If $f<0$, then the canonical numeral for $f$ is a minus sign (`$-$') followed by the
canonical numeral for $-f$.
\item If $f=0$, then the canonical numeral for $f$ is the digit `0' followed by a decimal
point (`$.$'), the digit `0', the letter `e' and the digit `0'.
\item If $f>0$, then let
$w$ and $e$ be the unique integers such that $f=w\cdot10^e$ and $w \bmod 10\neq 0$.
The canonical numeral for $f$ is the canonical numeral for $w$ with a decimal point
 (`$.$') inserted after the first digit, followed by the letter `e', followed
by the canonical numeral for $e+\lfloor\log_{10}w\rfloor$.
(Obviously $w>0$ and the canonical numeral for $w$ thus begins with a digit.)
\end{itemize}
\index{float!conversion to numeral|)}

\subsection{Numeral to float}

\label{section:numeral-to-float}
\index{float!conversion from numeral|(}
Given a sequence of characters, the number it denotes (if any) is defined as follows.
The sequence of characters should consist of
\begin{itemize}
\item a (possibly signed) decimal numeral, which we will call the whole number part;
\item a decimal point;
\item an unsigned decimal numeral, which we will call the fractional part;
\item optionally an `E' or `e' followed by a (possibly signed) decimal numeral,
which we will call the exponent.
\end{itemize}
If it does not, then the sequence of characters does not denote any number.

Let $e'$ be the number of digits in the fractional part,
let $w$ be the integer denoted by the concatenation of the whole number part and
the fractional part, and let $e$ be the integer denoted by the exponent, or
zero if there was no exponent part
(\S\ref{section:numeral-to-integer}).

The number in $F$ denoted by the sequence of characters is then
\[\mathit{result}_F(w\cdot10^{e-e'},\mathit{rnd}_F).\]

Note that this also defines the meaning of a
\NT{FloatLiteral}\index{FloatLiteral@\NT{FloatLiteral}}: if the sequence of characters
that it constitutes denotes $f\in F$, then the \NT{FloatLiteral} denotes $\Re[f]$.
\index{float!conversion from numeral|)}


\section{Summary and further reading}

This paper demonstrated a simple technique for building complex equality proofs by composing elementary equalities using transitivity. Understanding this approach allows the reader to learn more advanced techniques offered by dependently typed languages. Possible next steps include learning mechanisms offered by Agda's standard library, namely the \texttt{≡-Reasoning} located in \texttt{Relation.} \texttt{Binary.}\texttt{PropositionalEquality} module, which provides notation identical to the one introduced in Section~\ref{sec:eq-proofs-using-trans}. Another step to take is learning how to conduct proofs using tactics in languages such as Idris \cite{Bra13} or Coq \cite{coq}.

Due to space limitations some parts of the companion code were left out from the discussion. The reader may now wish to take a look at verification of priority invariant in two-pass and single-pass implementations of \texttt{merge} and simultaneous proofs of rank and priority invariants.


\documentclass[10pt]{article}
\usepackage{a4wide}
\usepackage{listings}
\usepackage{listings}
\newcommand{\be}{\begin{equation}}
\newcommand{\ee}{\end{equation}}
\newcommand{\OP}[1]{{\bf\widehat{#1}}}

\begin{document}

\section*{Project 2, Variational Monte Carlo studies of helium and beryllium}

The final aim of this project is to develop a variational Monte Carlo program which can be used to obtain ground state properties of atoms like He, Be, O, Ne, Si etc as well as diatomic molecules.
for important molecules

The aim of the second project  is to parallelize the code from project 1 and implement an efficient algorithm for computing the Slater determinant. We will apply the new algorithm for the Slater determinant as well as a proper parallelization to the ground state of beryllium and neon.

{\bf The deadline for project 2 is March 27, at noon}.  See below for delivery format.

\section*{Variational Monte Carlo calculations of the beryllium and the neon atoms}
Project 1 has prepared you for extending your calculational machinery  to other systems.
Here we will focus on the  beryllium and neon atoms.
It is convenient to make modules or classes of trial wave functions, both many-body wave functions
and single-particle wave functions  and the quantum numbers  involved, such as spin, orbital momentum and principal
quantum numbers.

If we stick to hydrogen-like wave functions,
the trial wave function for Beryllium can be written as
\begin{equation}
   \psi_{T}({\bf r_1},{\bf r_2}, {\bf r_3}, {\bf r_4}) =
   Det\left(\phi_{1}({\bf r_1}),\phi_{2}({\bf r_2}),
   \phi_{3}({\bf r_3}),\phi_{4}({\bf r_4})\right)
   \prod_{i<j}^{4}\exp{\left(\frac{r_{ij}}{2(1+\beta r_{ij})}\right)},
\end{equation}
where $Det$ is a Slater determinant and the single-particle wave functions
are the hydrogen wave functions for the $1s$ and $2s$ orbitals. Their form
within the variational ansatz are given by
\begin{equation}
\phi_{1s}({\bf r_i}) = e^{-\alpha r_i},
\end{equation}
and
\begin{equation}
\phi_{2s}({\bf r_i}) = \left(1-\alpha r_i/2\right)e^{-\alpha r_i/2}.
\end{equation}

For the correlation part
\[
\Psi_C=\prod_{i< j}g(r_{ij})= \exp{\left\{\sum_{i<j}\frac{ar_{ij}}{1+\beta r_{ij}}\right\}},
\]
we need to take into account whether electrons have equal or opposite spins since we have to obey the
electron-electron cusp condition as well.  For Beryllium, as an example,  you can fix electrons 1 and 2 to have spin up while
electrons 3 and 4 have spin down.
When the electrons have  equal spins
\[
a= 1/4,
\]
while for opposite spins (as for the ground state of  helium)
\[
a= 1/2.
\]

For neon, the trial wave function can take the form
\begin{equation}
   \psi_{T}({\bf r_1},{\bf r_2}, \dots,{\bf r_{10}}) =
   Det\left(\phi_{1}({\bf r_1}),\phi_{2}({\bf r_2}),
   \dots,\phi_{10}({\bf r_{10}})\right)
   \prod_{i<j}^{10}\exp{\left(\frac{r_{ij}}{2(1+\beta r_{ij})}\right)},
\end{equation}
In this case you need to include the $2p$ wave function as well.
It is given as
\begin{equation}
\phi_{2p}({\bf r_i}) = \alpha {\bf r_i}e^{-\alpha r_i/2}.
\end{equation}
Observe that $r_i = \sqrt{r_{i_x}^2+r_{i_y}^2+r_{i_z}^2}$.

\begin{enumerate}
\item[(a)]   Write a function which sets up the Slater determinant for beryllium and neon.
Compute the ground state energies for beryllium and neon as you did in project 1.
The calculations should include  blocking and importance sampling using the closed form expression for the local energy.

\item[(b)] The next step is to parallelize your code using either OpenMP or MPI.
Test whether your code as an optimal speed-up or not.
Implement unit tests as well in your program.

\item[c)]  With the optimal parameters for the ground state wave function, compute again the onebody density for beryllium. Compute the onebody density for neon as well. Discuss your results and compare the results with those obtained with a pure hydrogenic wave functions. Run a Monte Carlo calculations without the Jastrow factor as well
and compute the same quantities. How important are the correlations induced by the Jastrow factor?

\end{enumerate}

\section*{How to write the report}
What should the report contain and how can I structure it? A typical structure follows here.
\begin{itemize}
\item An abstract with the main findings.
\item  An introduction where you explain the aims and rationale for the physics case and what you have done. At the end of the introduction you should give a brief summary of the structure of the report
\item Theoretical models and technicalities. This sections ends often being the methods section.
\item Results and discussion
\item Conclusions and perspectives
\item Appendix with extra material
\item Bibliography
\end{itemize}
Keep always a good log of what you do.

\subsection*{What should I focus on? Introduction.}
You don't need to answer all questions in a chronological order. When you write the introduction you could focus on the following aspects
\begin{itemize}
\item Motivate the reader, the first part of the introduction gives always a motivation and tries to give the overarching ideas
\item What I have done
\item The structure of the report, how it is organized etc
\end{itemize}
\subsection*{What should I focus on? Methods sections.}
\begin{itemize}
\item Describe the methods and algorithms
\item You need to explain how you implemented the methods and also say something about the structure of your algorithm and present some parts of your code
\item You should plug in some calculations to demonstrate your code, such as selected runs used to validate and verify your results. The latter is extremely important!! A reader needs to understand that your code reproduces selected benchmarks and reproduces previous results, either numerical and/or well-known closed form expressions.
\end{itemize}

\subsection*{What should I focus on? Results sections.}
\begin{itemize}
\item Present your results
\item Give a critical discussion of your work and place it in the correct context.
\item Relate your work to other calculations/studies
\item An eventual reader should be able to reproduce your calculations if she/he wants to do so. All input variables should be properly explained.
\item Make sure that figures and tables contain enough information in their captions, axis labels etc so that an eventual reader can gain a first impression of your work by studying figures and tables only.
\end{itemize}

\subsection*{What should I focus on? Conclusions sections.}
\begin{itemize}
\item State your main findings and interpretations
\item Try as far as possible to present perspectives for future work
\item Try to discuss the pros and cons of the methods and possible improvements
\end{itemize}

\subsection*{What should I focus on? Additional material, appendices.}
\begin{itemize}
\item Additional calculations used to validate the codes
\item Selected calculations, these can be listed with few comments
\item Listing of the code if you feel this is necessary
\item You can consider moving parts of the material from the methods section to the appendix. You can also place additional material on your webpage.
\end{itemize}
\subsection*{What should I focus on? References.}
\begin{itemize}
\item Give always references to material you base your work on, either scientific articles/reports or books.
\item Refer to articles as: name(s) of author(s), journal, volume (boldfaced), page and year in parenthesis.
\item Refer to books as: name(s) of author(s), title of book, publisher, place and year, eventual page numbers
\end{itemize}

\section*{Format for electronic delivery of report and programs}
%
Your are free to choose your format for handing in. The simplest way is that you send us your github link that contains the report in your chosen format(pdf, ps, docx, ipython notebook etc) and the programs.
As programming language you have to choose either C++ or Fortran or Python. We recommend C++ or Fortran.
Finally,
we recommend that you work together. Optimal working groups consist of
2-3 students, but more people can collaborate. You can then hand in a common report.

\section*{Literature}
\begin{enumerate}
\item B.~L.~Hammond, W.~A.~Lester and P.~J.~Reynolds, Monte Carlo methods
in Ab Inition Quantum Chemistry, World Scientific, Singapore, 1994, chapters
2-5 and appendix B.

\item B.H.~Bransden and C.J.~Joachain, Physics of Atoms and molecules,
Longman, 1986. Chapters 6, 7 and 9.
\item S.A.~Alexander and R.L.~Coldwell,
Int.~Journal of Quantum Chemistry, {\bf 63} (1997) 1001.  This article is available
at the webpage of the course as the file jastrow.pdf under the project 1 link.
\item C.J.~Umrigar, K.G.~Wilson and J.W.~Wilkins, Phys.~Rev.~Lett.~{\bf 60}
(1988) 1719.

\end{enumerate}

\section*{Unit tests, how and why?}
Unit Testing is the practice of testing the smallest testable parts, called units, of an application individually and independently to determine if they behave exactly as expected. Unit tests (short code fragments) are usually written such that they can be preformed at any time during the development to continually verify the behavior of the code. In this way, possible bugs will be identified early in the development cycle, making the debugging at later stage much easier. There are many benefits associated with Unit Testing, such as
\begin{itemize}
\item It increases confidence in changing and maintaining code. Big changes can be made to the code quickly, since the tests will ensure that everything still is working properly.
\item Since the code needs to be modular to make Unit Testing possible, the code will be easier to reuse. This improves the code design.
\item Debugging is easier, since when a test fails, only the latest changes need to be debugged.
\item Different parts of a project can be tested without the need to wait for the other parts to be available.
\item A unit test can serve as a documentation on the functionality of a unit of the code.
\end{itemize}
Here follows a simple example, see the website of the course for more information on how to install unit test libraries.
\begin{verbatim}
#include <unittest++/UnitTest++.h>

class MyMultiplyClass{
public:
   double multiply(double x, double y) {
      return x * y;
   }
};
TEST(MyMath) {
     MyMultiplyClass my; CHECK_EQUAL(56, my.multiply(7,8));
}
int main()
{
return UnitTest::RunAllTests();
}
\end{verbatim}
For Fortran users, the link at \url{http://sourceforge.net/projects/fortranxunit/} contains a similar software for unit testing.
\end{document}


% This is a model template for the solutions in computational science. You can find a very useful documentation for LaTeX in Finnish at ftp://ftp.funet.fi/pub/TeX/CTAN/info/lshort/finnish/ or in English at ftp://ftp.funet.fi/pub/TeX/CTAN/info/lshort/english/. The section List of mathematical symbols in Chapter 3 is especially useful for the typesetting of mathematical formulas.

% Compile the document to PDF by command 'pdflatex model.tex' in the terminal. The command must be run twice for the references in the text to be correct.

\documentclass[a4paper,11pt]{article}
\usepackage[utf8]{inputenc}
% This includes letters such as � and �
\usepackage[T1]{fontenc}
% Use here 'Finnish' for Finnish hyphenation. You may have to compile the code twice after the change.
\usepackage[english]{babel}
\usepackage{graphicx}
% Some math stuff
\usepackage{amsmath,amsfonts,amssymb,amsbsy,commath,booktabs,hyperref,dirtytalk}
% This is just to include the urls
\usepackage{hyperref,subcaption}
\usepackage[margin=2cm]{geometry}

\setlength{\parindent}{0mm}
\setlength{\parskip}{1.0\baselineskip}

\usepackage{listings}
\usepackage{color}
\usepackage{pdfpages}

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}

\lstset{frame=tb,
	language=Python,
	aboveskip=3mm,
	belowskip=3mm,
	showstringspaces=false,
	columns=flexible,
	basicstyle={\tiny\ttfamily},
	numbers=none,
	numberstyle=\tiny\color{gray},
	keywordstyle=\color{blue},
	commentstyle=\color{dkgreen},
	stringstyle=\color{mauve},
	breaklines=true,
	breakatwhitespace=true,
	tabsize=4
}

\begin{document}

\title{Becs-114.1100 Computational Science -- exercise round 9} % Replace the exercise round number
\author{Kunal Ghosh, 546247} % Replace with your name and student number
\maketitle
\section{Solution 1}
\subsection{Pencil and Paper Problem}
Assuming that we are using the Monte Carlo method to estimate the value of a given quantity A where One simulation run gives a single numerical value denoted by $A_{i}$ and by running the simulation n times we get the set $\{A_{i}\}_{i=1}^{n}$
\subsubsection{Obtaining a reliable estimate of the true value of A}
We can get a reliable estimate of the value of $A$ by drawing more samples $A_{i}$. In other words, as we keep increasing the value of $n$ our precision keeps on increasing.\\
This is an extension of the fact that, if you run $m$ simulations $k$ times to get an estimate $E_{1}$. Or if you run $k$ simulations $m$ times to get an estimate $E_{2}$\\The precision of $E_{1}$ and $E_{2}$ remains the same.
\subsubsection{How to calculate an estimate of the error?}
We can calculate the statistical error
\begin{equation}
    \sigma \approx \frac{\sigma_{n}}{\sqrt{N}}
\end{equation}
where $\sigma_{n}$ is the standard deviation over $n$ samples calculated by using the formula
\begin{equation}
\sigma_{N}^{2} = \text{(Second Moment)} - \text{(First Moment)}^{2}
\end{equation}
In the equation above we are calculating the moments of the sequence of $\{A_{i}\}$s
\subsubsection{How is the central limit theorem related to the estimation ?}
According to the Central limit theorem:
\\
\textit{For any independently measured values $M_{1},M_{2},...,M_{m}$ which come from the same (sufficiently short-ranged) distribution p(x), the average
\begin{equation}
    \langle M \rangle  = \frac{1}{m}\sum_{i=1}^{m}M_{i}
\end{equation}
will asymptotically follow a \textbf{Gaussian distribution} (normal distribution) whose mean is $\langle M \rangle$ (equal to the mean of the parent distribution p(x)) and variance is $\frac{1}{\sqrt{N}}$ times that of p(x).}

In our estimation problem each $A_{i}$ can be thought of as an independent measurement from a distribution around A. ( i.e. A$\pm$noise )\\
Then according to the central limit theorem the mean of the samples asymptotically would be the mean of the parent distribution, which is the mean of the distribution around A which is almost equal to A (asymptotically).\\
Also from the central limit theorem, the variance would be $\frac{1}{\sqrt{N}}$ times that of the parent distribution. We can use this to measure the statistical error in our measure and identify the value of A with a desired precision.

\subsection{Estimating the value of $\pi$ using "Hit-or-Miss" method}\label{prob1b}
\begin{figure}[ht]
	\centering
    \includegraphics[scale=0.80]{pi_est.png}
    \caption{Estimate of the values of $\pi$}
	\label{fig:Y1}
\end{figure}

\begin{figure}[ht]
	\centering
    \includegraphics[scale=0.80]{err_est.png}
    \caption{change of error estimate and absolute error with increasing values of N. Here log($\frac{1}{\sqrt{N}}$) has been plotted for reference.}
	\label{fig:Y2}
\end{figure}

\begin{table}[ht]
\centering
\label{1b}
\begin{tabular}{|c|c|c|c|}
\hline
\textbf{N} & \textbf{Pi Estimate}&\textbf{$\log(\frac{\sigma}{\sqrt{N}}$)}&\textbf{Average Absolute Error} \\ \hline
1000 & 3.142508 & -6.41348792121 & -6.99620842209 \\
2000 & 3.139988 & -6.71147219026 & -6.43484712196 \\
3000 & 3.14166 & -6.91763448245 & -9.60566704811 \\
4000 & 3.141022 & -7.08901447367 & -7.46872748644 \\
5000 & 3.1420576 & -7.25796392872 & -7.67358928815 \\
6000 & 3.14161333333 & -7.2936121459 & -10.7863757461 \\
7000 & 3.14190171429 & -7.38430359819 & -8.0819742007 \\
8000 & 3.1407535 & -7.41917293679 & -7.08311631649 \\
9000 & 3.14193244444 & -7.55625404967 & -7.98718147024 \\
10000 & 3.1406948 & -7.59155617352 & -7.0155030864 \\
11000 & 3.14247527273 & -7.63964380553 & -7.03261724305 \\
12000 & 3.14126566667 & -7.66343122719 & -8.0255891238 \\
13000 & 3.14190461538 & -7.71002347021 & -8.07263114507 \\
14000 & 3.14225 & -7.7644752777 & -7.32730004188 \\
15000 & 3.142104 & -7.74859962632 & -7.57846409317 \\
16000 & 3.14134375 & -7.82647958467 & -8.29844327801 \\
17000 & 3.14103223529 & -7.8432896092 & -7.48682636454 \\
18000 & 3.14201311111 & -7.82393930635 & -7.77416807873 \\
19000 & 3.14135894737 & -7.91094478818 & -8.36144394036 \\
20000 & 3.1413314 & -7.94131111675 & -8.2500174438 \\
21000 & 3.14112952381 & -7.93669418525 & -7.67750235447 \\
22000 & 3.14191890909 & -7.94388132238 & -8.02783099513 \\
23000 & 3.141428 & -7.94778029614 & -8.71166425548 \\
24000 & 3.14099083333 & -7.95348895198 & -7.41555105294 \\
25000 & 3.14187184 & -8.01644609615 & -8.1836323316 \\
26000 & 3.141922 & -8.01782795101 & -8.01840168809 \\
27000 & 3.1415082963 & -8.05814633533 & -9.38044442293 \\
28000 & 3.14157214286 & -8.0804222317 & -10.7945422655 \\
29000 & 3.14181075862 & -8.11554628555 & -8.43053569888 \\
30000 & 3.14137533333 & -8.13521894018 & -8.43413656861 \\
\hline
\end{tabular}
\caption{Table of Values for the $\pi$ esimate using Monte Carlo Simulations.}
\end{table}
\textbf{What relation does the error estimate follow?}
\\It goes down as $\frac{1}{\sqrt{N}}$ with the number of iterations N. As can be seen in \ref{fig:Y2}
\\\textbf{What about the absolute error?}
\\The absolute error goes down approximately linearly.

The corresponding python code can be found at \ref{code:problem1b}
\clearpage
\section{Solution Q3}\label{prob3}
In this problem we are trying to Identify which meathod, Importance Sampling or Sample Mean method, we should choose for the task of identifying integrals given a function and its limits. To choose between them, we use each of the methods to perform a definite integral $\int_{1}^{2} (2x^{8}-1) dx$. After executing both the methods, we plot their respective absolute error with the analytically calculated exact integral value of 112.5555 We then state our conclusion below.
\begin{figure}[ht]
	\centering
    \includegraphics[scale=0.80]{Integrals.png}
    \caption{Value of Integral calculated using Importance sampling and Sample Mean method as a function of the Number of random samples. The exact value is plotted in Red for comparison.}
	\label{fig:errors}
\end{figure}

\begin{figure}[ht]
	\centering
    \includegraphics[scale=0.80]{Errors.png}
    \caption{Absolute errors of Integrals calculated using Importance sampling and Sample mean method, when compared to the actual analytic integral. The values have been plotted in the log scale}
	\label{fig:errors}
\end{figure}

\begin{table}[ht]
\centering
\label{table:1b}
\begin{tabular}{|c|c|c|c|c|}
\hline
\textbf{N} & \textbf{Imp samp est}&\textbf{Abs Err Imp Samp}&\textbf{Sample Mean Est}&\textbf{Abs Err Sample Mean} \\ \hline
    100 & 112.817602096 & 0.262046540193 & 97.6200018902 & 14.9355536653 \\
    115 & 112.790934035 & 0.235378479495 & 110.387517365 & 2.1680381906 \\
    133 & 112.862782704 & 0.307227148659 & 124.198178589 & 11.6426230335 \\
    153 & 112.307040131 & 0.248515424259 & 116.378833157 & 3.8232776018 \\
    176 & 112.570447868 & 0.01489231282 & 115.172083115 & 2.6165275593 \\
    202 & 112.807401366 & 0.251845810884 & 108.951693299 & 3.60386225665 \\
    233 & 112.605799413 & 0.0502438576779 & 106.077739978 & 6.47781557707 \\
    268 & 112.727453517 & 0.171897961599 & 128.263364923 & 15.7078093672 \\
   ...&...&...&...&...\\
    720 & 112.425498173 & 0.130057382117 & 104.21269517 & 8.3428603851 \\
    7906 & 112.591896217 & 0.0363406610969 & 111.628379791 & 0.927175764348 \\
    9103 & 112.593672719 & 0.0381171632268 & 115.933335012 & 3.37777945607 \\
    10481 & 112.593388655 & 0.0378330998116 & 110.255123721 & 2.30043183446 \\
    12068 & 112.544424017 & 0.0111315383437 & 112.60262766 & 0.0470721040552 \\
    13895 & 112.578383621 & 0.0228280654867 & 112.317530107 & 0.238025448329 \\
    15999 & 112.57870659 & 0.0231510344667 & 114.266579722 & 1.71102416604 \\
    18421 & 112.584252555 & 0.0286969996644 & 113.82109461 & 1.26553905427 \\
    21210 & 112.567439326 & 0.011883770476 & 111.959205762 & 0.596349793541 \\
    24421 & 112.525425965 & 0.0301295907316 & 113.264044066 & 0.708488510236 \\
    28118 & 112.565090954 & 0.00953539796538 & 113.32274423 & 0.767188674465 \\
    32375 & 112.543195441 & 0.0123601148601 & 111.961554588 & 0.594000967337 \\
    37276 & 112.56452844 & 0.00897288431986 & 113.132173579 & 0.576618023773 \\
    42919 & 112.553776654 & 0.00177890148414 & 112.70115021 & 0.145594654239 \\
    49417 & 112.553603269 & 0.00195228660451 & 112.926394176 & 0.370838620377 \\
    56899 & 112.549206334 & 0.006349221845 & 111.432828844 & 1.12272671195 \\
    65513 & 112.583406579 & 0.0278510230071 & 112.367194506 & 0.188361049716 \\
    75431 & 112.544776726 & 0.0107788296986 & 113.524978805 & 0.969423249651 \\
    86851 & 112.561721621 & 0.00616606549636 & 112.540220207 & 0.0153353481125 \\
    100000 & 112.555043138 & 0.000512417685144 & 112.505272248 & 0.0502833078437 \\
\hline
\end{tabular}
\caption{Table showing the values of $\int_{1}^{2} (2x^{8}-1) dx$ Estimated using Importance sampling method, its Absolute Error followed by the values using Sample Mean Method and then its Absolute Error in the last column.}
\end{table}
\textbf{Which method is better?}
It can be seen from the graph above and also from the table of values below, that the absolute error achieved by Importance sampling is much lower than that achieved by sample mean method. Hence \textbf{Importance Sampling} method is better.
\\The corresponding python code can be found at \ref{code:problem3}
\clearpage
\section{Appendix A}\label{code:problem1b}
Python source code for \ref{prob1b}.
{\footnotesize
\begin{lstlisting}

from __future__ import division
import numpy as np
import pylab as pl

def mc_circle_np(n):
    '''
    We would be drawing random samples from -1 to 1
    '''
    inside = 0
    x = np.random.random(n)*2-1
    y = np.random.random(n)*2-1
    inside = np.sum((np.square(x,out=x) + np.square(y,out=y)) < 1)
    return 4 * (inside/n)

if __name__ == '__main__':
    n = 1000
    pi = 3.141592654
    pi_est = []
    err_est = []
    avg_abs_err = []
    start,end,step = 1000,31000,1000
    for N in xrange(start,end,step):
        pis = np.zeros(n)
        for i in xrange(1000):
            pis[i] = mc_circle_np(N)
        pi_est_m = np.mean(pis)
        pi_est.append(pi_est_m)
        err_est_m = np.log(np.std(pis)/np.sqrt(n)) #Because we always have n (=1000) estimates
        err_est.append(err_est_m)
        avg_abs_err_m = np.log(np.abs(pi_est_m - pi))
        avg_abs_err.append(avg_abs_err_m)
        print("{} & {} & {} & {} \\\\".format(N,pi_est_m,err_est_m,avg_abs_err_m))

    pl.plot(pi_est)
    pl.ylabel("Pi Estimate")
    pl.ylim((3.1,3.2))
    pl.xlabel("Iterations")
    pl.grid()
    pl.savefig("pi_est.png")

    pl.figure()
    pl.plot(err_est)
    pl.plot(avg_abs_err)
    pl.xlabel("Iterations")
    pl.legend(["Error Estimate","Average Absolute Err"])
    pl.grid()
    pl.savefig("err_est.png")
    pl.show()

\end{lstlisting}
}
\clearpage
\section{Appendix B}\label{code:problem3}
Python source code \ref{prob3}.
{\footnotesize
\begin{lstlisting}

from __future__ import division
import numpy as np
import pylab as pl

one_by_nine = 1/9.0
nine_by_511 = 9/511.0
def getIest_Imp(N):
    y = np.random.random(N)
    # Inverse function calculated manually
    x = np.power(511*y + 1, one_by_nine)
    f = 2*np.power(x,8) -1
    w = nine_by_511 * np.power(x,8)
    Iest = np.mean(np.true_divide(f,w))
    return Iest

def getIest_Sm(N):
    # b = 2 and a = 1 Hence b-a = 1
    # which doesn't affect the integral
    # has been omitted from the calculations
    x = np.random.random(N)+1 # shift the rnadom values between 1 and 2
    f = 2*np.power(x,8)-1
    Iest = np.mean(f)
    return Iest

if __name__ == '__main__':
    exact = 1013/9.0
    Iest_Imp = []
    absErr_Imp = []
    Iest_Sm = []
    absErr_Sm = []
    Ns = map(lambda x: int(round(x)), np.logspace(2, 5, 50))
    for N in Ns:
        estImp = getIest_Imp(N)
        Iest_Imp.append(estImp)
        errImp = abs(exact-estImp)
        absErr_Imp.append(errImp)

        estSm = getIest_Sm(N)
        Iest_Sm.append(estSm)
        errSm = abs(exact-estSm)
        absErr_Sm.append(errSm)

        print "{} & {} & {} & {} & {} \\\\".format(N,estImp,errImp,estSm,errSm)

    pl.loglog(Ns,absErr_Imp,label="Importance Sampling")
    pl.loglog(Ns,absErr_Sm,label="Sample Mean")
    pl.loglog(Ns,map(lambda x:1/(x**0.5),Ns),label="1/sqrt(N)")
    pl.legend(framealpha=0.5)
    pl.xlabel("Ns")
    pl.ylabel("Absolute Errors")

    pl.savefig("Errors.png")
    pl.show()
\end{lstlisting}
}
\end{document}


% This LaTeX was auto-generated from an M-file by MATLAB.
% To make changes, update the M-file and republish this document.

\subsection*{gpr.m}

\begin{par}
\textbf{Summary:} Gaussian process regression, with a named covariance function. Two modes are possible: training and prediction: if no test data are given, the function returns minus the log likelihood and its partial derivatives with respect to the hyperparameters; this mode is used to fit the hyperparameters. If test data are given, then (marginal) Gaussian predictions are computed, whose mean and variance are returned. Note that in cases where the covariance function has noise contributions, the variance returned in S2 is for noisy test targets; if you want the variance of the noise-free latent function, you must substract the noise variance.
\end{par} \vspace{1em}
\begin{par}
usage: [nlml dnlml] = gpr(logtheta, covfunc, x, y)    or: [mu S2]  = gpr(logtheta, covfunc, x, y, xstar)
\end{par} \vspace{1em}
\begin{par}
where:
\end{par} \vspace{1em}
\begin{verbatim}logtheta is a (column) vector of log hyperparameters
covfunc  is the covariance function
x        is a n by D matrix of training inputs
y        is a (column) vector (of size n) of targets
xstar    is a nn by D matrix of test inputs
nlml     is the returned value of the negative log marginal likelihood
dnlml    is a (column) vector of partial derivatives of the negative
              log marginal likelihood wrt each log hyperparameter
mu       is a (column) vector (of size nn) of prediced means
S2       is a (column) vector (of size nn) of predicted variances\end{verbatim}
\begin{par}
For more help on covariance functions, see "help covFunctions".
\end{par} \vspace{1em}
\begin{par}
(C) Copyright 2006 by Carl Edward Rasmussen (2006-03-20).
\end{par} \vspace{1em}

\begin{lstlisting}
function [out1, out2] = gpr(logtheta, covfunc, x, y, xstar)
\end{lstlisting}

\subsection*{Code}

\begin{lstlisting}
if ischar(covfunc), covfunc = cellstr(covfunc); end % convert to cell if needed
[n, D] = size(x);
if eval(feval(covfunc{:})) ~= size(logtheta, 1)
  error('Error: Number of parameters do not agree with covariance function')
end

K = feval(covfunc{:}, logtheta, x);    % compute training set covariance matrix

L = chol(K)';                        % cholesky factorization of the covariance
alpha = solve_chol(L',y);

if nargin == 4 % if no test cases, compute the negative log marginal likelihood

  out1 = 0.5*y'*alpha + sum(log(diag(L))) + 0.5*n*log(2*pi);

  if nargout == 2               % ... and if requested, its partial derivatives
    out2 = zeros(size(logtheta));       % set the size of the derivative vector
    W = L'\(L\eye(n))-alpha*alpha';                % precompute for convenience
    for i = 1:length(out2)
      out2(i) = sum(sum(W.*feval(covfunc{:}, logtheta, x, i)))/2;
    end
  end

else                    % ... otherwise compute (marginal) test predictions ...

  [Kss, Kstar] = feval(covfunc{:}, logtheta, x, xstar);     %  test covariances

  out1 = Kstar' * alpha;                                      % predicted means

  if nargout == 2
    v = L\Kstar;
    out2 = Kss - sum(v.*v)';
  end

end
\end{lstlisting}


\index{quantHeuristicsLib|(}
\index{Quantifier Instantiation|see {quantHeuristicsLib}}

\setcounter{sessioncount}{0}

\subsection{Motivation}

Often interactive proofs can be simplified by instantiating
quantifiers. The \ml{Unwind} library\index{Unwind}, which is part of the simplifier allows
instantiations of ``trivial'' quantifiers:

\[ \forall x_1\ \ldots x_i \ldots x_n.\ P_1 \wedge \ldots \wedge x_i = c \wedge \ldots \wedge P_n \Longrightarrow Q \]
and
\[ \exists x_1\ \ldots x_i \ldots x_n.\ P_1 \wedge \ldots \wedge x_i =
c \wedge \ldots \wedge P_n \] can be simplified by
instantiating $x_i$ with $c$. Because unwind-conversions are
part of \holtxt{bool\_ss}, they are used with nearly every call of the simplifier
and often simplify proofs considerably. However, the \ml{Unwind} library can only handle these common cases. If the term structure is
only slightly more complicated, it fails. For example, $\exists x.\ P(x) \Longrightarrow (x = 2) \wedge Q(x)$
cannot be tackled.

There is also the \ml{Satisfy} library\index{Satisfy}, which uses
unification to show existentially quantified formulas. It can handle
problems like $\exists x.\ P_1(x,c_1)\ \wedge \ldots P_n(x,c_n)$ if
given theorems of the form $\forall x\ c.\ P_i(x, c)$. This is often
handy, but still rather limited.

The quantifier heuristics library (\ml{quantHeuristicsLib}) provides more power
and flexibility. A few simple examples of what it can do
are shown in Table~\ref{table_qh_examples}. Besides the power demonstrated
by these examples, the library is highly flexible as well.  At it's
core, there is a modular, syntax driven search for instantiation.
This search consists of a collection of interleaved heuristics.  Users
can easily configure existing heuristics and add own ones. Thereby, it
is easy to teach the library about new predicates, logical connectives
or datatypes.

\newcommand{\mytablehead}[1]{\\\multicolumn{2}{l}{\textit{#1}}\\}
\begin{table}[h]
\centering\scriptsize
\begin{tabular}{lll}
\textbf{Problem} & \textbf{Result} \\\hline

\mytablehead{basic examples}
$\exists x.\ x = 2 \wedge P (x)$ & $P(2)$ \\
$\forall x.\ x = 2 \Longrightarrow P (x)$ & $P(2)$ \\

\mytablehead{solutions and counterexamples}
$\exists x.\ x = 2$ & $\textit{true}$ \\
$\forall x.\ x = 2$ & $\textit{false}$ \\

\mytablehead{complicated nestings of standard operators}
$\exists x_1. \forall x_2.\ (x_1 = 2) \wedge P(x_1, x_2)$ &
$\forall x_2.\ P(2, x_2)$ \\

$\exists x_1, x_2.\ P_1(x_2) \Longrightarrow (x_1 = 2) \wedge P(x_1, x_2)$ &
$\exists x_2.\ P_1(x_2) \Longrightarrow P(2, x_2)$ \\
$\exists x.\ ((x = 2) \vee (2 = x)) \wedge P(x)$ & $P(2)$ \\

\mytablehead{exploiting unification}
$\exists x.\ (f (8 + 2) = f (x + 2)) \wedge P (f(10))$ & $P (f(10))$ \\
$\exists x.\ (f (8 + 2) = f (x + 2)) \wedge P (f(x + 2))$ & $P (f(8 + 2))$ \\
$\exists x.\ (f (8 + 2) = f (x + 2)) \wedge P (f(x))$ & - (\textrm{no instantiation found}) \\

\mytablehead{partial instantiation for datatypes}
$\forall p.\ c = \textsf{FST}(p) \Longrightarrow P(p)$ & $\forall p_2.\ P(c, p_2)$ \\

$\forall x.\ \textsf{IS\_NONE}(x) \vee P(x)$ & $\forall x'.\ P (\textsf{SOME}(x'))$ \\

$\forall l.\ l \neq [\,] \Longrightarrow P(l)$ & $\forall \textit{hd}, \textit{tl}.\
P(\textit{hd} :: \textit{tl})$ \\

\mytablehead{context}
$P_1(c) \Longrightarrow \exists x.\ P_1(x) \vee P_2(x)$ & \textit{true} \\
$P_1(c) \Longrightarrow \forall x.\ \neg P_1(x) \wedge P_2(x)$ & $\neg P_1(c)$ \\

$(\forall x.\ P_1(x) \Rightarrow (x = 2)) \Longrightarrow (\forall x.\ P_1(x) \Rightarrow P_2(x))$ &
$(\forall x.\ P_1(x) \Rightarrow (x = 2)) \Rightarrow (P_1(2) \Rightarrow P_2(2))$ \\

$\big((\forall x.\ P_1(x) \Rightarrow P_2(x)) \wedge P_1(2)\big) \Longrightarrow \exists x.\ P_2(x)$ &
\textit{true} \\
\hline
\end{tabular}
\caption{Examples}
\label{table_qh_examples}
\end{table}

\subsection{User Interface}\label{sec_interface}

The quantifier heuristics library can be found in the sub-directory
\holtxt{src/quantHeuristics}.  The entry point to the framework is the
library \holtxt{quantHeuristicsLib}.

\subsubsection{Conversions}
Usually the library is used for
converting a term containing quantifiers to an equivalent one. For this,
the following high level entry points exists:
\bigskip

\noindent
\begin{tabular}{@{}ll}
\texttt{QUANT\_INSTANTIATE\_CONV} & \texttt{: quant\_param list -> conv} \\
\texttt{QUANT\_INST\_ss} & \texttt{: quant\_param list -> ssfrag} \\
\texttt{QUANT\_INSTANTIATE\_TAC} & \texttt{: quant\_param list -> tactic} \\
\texttt{ASM\_QUANT\_INSTANTIATE\_TAC} & \texttt{: quant\_param list -> tactic}
\end{tabular}
\bigskip

All these functions get a list of \emph{quantifier heuristic parameters} as arguments. These
parameters essentially configure, which heuristics are used during the guess-search. If
an empty list is provided, the tools know about the standard Boolean combinators, equations and context.
\texttt{std\_qp} adds support for common datatypes like pairs or lists.
Quantifier heuristic parameters are explained in more detail in
Section~\ref{quantHeu_subsec_qps}.

So, some simple usage of the quantifier heuristic library looks like:

\begin{session}
\begin{verbatim}
- QUANT_INSTANTIATE_CONV [] ``?x. (!z. Q z /\ (x=7)) /\ P x``;
> val it = |- (?x. (!z. Q z /\ (x = 7)) /\ P x) <=> (!z. Q z) /\ P 7: thm

- QUANT_INSTANTIATE_CONV [std_qp] ``!x. IS_SOME x ==> P x``
> val it = |- (!x. IS_SOME x ==> P x) <=> !x_x'. P (SOME x_x'): thm
\end{verbatim}
\end{session}

Usually, the quantifier heuristics library is used together with the
simplifier using \holtxt{QUANT\_INST\_ss}. Besides interleaving
simplification and quantifier instantiation, this has the benefit of
being able to use context information collected by the simplifier:

\begin{session}
\begin{verbatim}
- QUANT_INSTANTIATE_CONV [] ``P m ==> ?n. P n``
Exception- UNCHANGED raised

- SIMP_CONV (bool_ss ++ QUANT_INST_ss []) [] ``P m ==> ?n. P n``
> val it = |- P m ==> (?n. P n) <=> T: thm
\end{verbatim}
\end{session}

It's usually best to use \holtxt{QUANT\_INST\_ss}
together with e.\,g.\ \holtxt{SIMP\_TAC} when using the library with tactics.
However, if free variables of the goal should be instantiated, then
\holtxt{ASM\_QUANT\_INSTANTIATE\_TAC} should be used:

\begin{session}
\begin{verbatim}
P x
------------------------------------
  IS_SOME x
  : proof

- e (ASM_QUANT_INSTANTIATE_TAC [std_qp])
> P (SOME x_x') : proof
\end{verbatim}
\end{session}

There is also \holtxt{QUANT\_INSTANTIATE\_TAC}. This tactic does not
instantiate free variables. Neither does it take assumptions into consideration.
It is just a shortcut for using \holtxt{QUANT\_INSTANTIATE\_CONV} as a tactic.

\subsubsection{Unjustified Guesses}

Most heuristics justify the guesses they produce and therefore allow to
prove equivalences of e.\,g.\ the form $\exists x.\ P(x) \Leftrightarrow P(i)$.
However, the implementation also supports unjustified guesses, which may be bogus.
Let's consider e.\,g.\ the formula $\exists x.\ P(x) \Longrightarrow (x = 2)\ \wedge\ Q(x)$.
Because nothing is known about $P$ and $Q$, we can't find a safe instantiation for $x$ here.
However, $2$ looks tempting and is probably sensible in many situations. (Counterexample:
$P(2)$, $\neg Q(2)$ and $\neg P(3)$ hold)

\texttt{implication\_concl\_qp} is a quantifier parameter that looks for valid guesses in the conclusion of an implication.
Then, it assumes without justification that these guesses are probably sensible for the whole implication as well.
Because these guesses might be wrong, one can either use implications or
expansion theorems like $\exists x.\ P(x)\ \Longleftrightarrow (\forall x.\ x \neg c \Rightarrow \neg P(x)) \Rightarrow P(c)$.

\begin{session}
\begin{verbatim}
- QUANT_INSTANTIATE_CONV [implication_concl_qp]
     ``?x. P x ==> (x = 2) /\ Q x``
Exception- UNCHANGED raised

- QUANT_INSTANTIATE_CONSEQ_CONV [implication_concl_qp]
     CONSEQ_CONV_STRENGTHEN_direction
     ``?x. P x ==> (x = 2) /\ Q x``
> val it =
   |- (P 2 ==> Q 2) ==> ?x. P x ==> (x = 2) /\ Q x: thm

- EXPAND_QUANT_INSTANTIATE_CONV [implication_concl_qp]
    ``?x. P x ==> (x = 2) /\ Q x``
> val it = |- (?x. P x ==> (x = 2) /\ Q x) <=>
              (!x. x <> 2 ==> ~(P x ==> (x = 2) /\ Q 2)) ==> P 2 ==> Q 2

- SIMP_CONV (std_ss++EXPAND_QUANT_INST_ss [implication_concl_qp]) []
    ``?x. P x ==> (x = 2) /\ Q x``
> val it =
   |- (?x. P x ==> (x = 2) /\ Q x) <=>
      (!x. x <> 2 ==> P x) ==> P 2 ==> Q 2: thm
\end{verbatim}
\end{session}

The following entry points should be used to exploit unjustified guesses:
\bigskip

\noindent
\begin{tabular}{@{}ll}
\texttt{QUANT\_INSTANTIATE\_CONSEQ\_CONV} & \texttt{: quant\_param list -> directed\_conseq\_conv} \\
\texttt{EXPAND\_QUANT\_INSTANTIATE\_CONV} & \texttt{: quant\_param list -> conv} \\
\texttt{EXPAND\_QUANT\_INST\_ss} & \texttt{: quant\_param list -> ssfrag} \\
\texttt{QUANT\_INSTANTIATE\_CONSEQ\_TAC} & \texttt{: quant\_param list -> tactic}
\end{tabular}

\subsubsection{Explicit Instantiations}

A special (degenerated) use of the framework, is turning guess search off completely and
providing instantiations explicitly. The tactic \holtxt{QUANT\_TAC} allows this. This means that
it allows to partially instantiate quantifiers at subpositions
with explicitly given terms. As such, it can be seen as
a generalisation of \holtxt{EXISTS\_TAC}\index{EXISTS\_TAC}.
%
\begin{session}
\begin{verbatim}
- val it = !x. (!z. P x z) ==> ?a b.    Q a        b z : proof

> e( QUANT_INST_TAC [("z", `0`, []), ("a", `SUC a'`, [`a'`])] )
- val it = !x. (    P x 0) ==> ?  b a'. Q (SUC a') b z : proof
\end{verbatim}
\end{session}
%
This tactic is implemented using unjustified guesses. It normally
produces implications, which is fine when used as a tactic. There is
also a conversion called \holtxt{INST\_QUANT\_CONV} with the same
functionality. For a conversion, implications are
problematic. Therefore, the simplifier and Metis are used to prove
the validity of the explicitly given instantiations. This succeeds
only for simple examples.

\subsection{Quantifier Heuristic Parameters}\label{quantHeu_subsec_qps}

Quantifier heuristic parameters play a similar role for the quantifier
instantiation library as simpsets do for the simplifier. They contain
theorems, ML code and general configuration parameters that allow to configure
guess-search. There are predefined parameters that handle
common constructs and the user can define own parameters.

\subsubsection{Quantifier Heuristic Parameters for Common Datatypes}

There are \holtxt{option\_qp}, \holtxt{list\_qp}, \holtxt{num\_qp} and \holtxt{sum\_qp} for option types, lists,
natural numbers and sum types respectively.
Some examples are displayed in the following table:
%
\[\begin{array}{r@{\quad \Longleftrightarrow \quad}l}
\forall x.\ \holtxt{IS\_SOME}(x) \Rightarrow P(x) & \forall x'.\ P (\holtxt{SOME}(x')) \\
\forall x.\ \holtxt{IS\_NONE}(x)& \textit{false} \\
\forall l.\ l \neq [\,] \Rightarrow P(l)& \forall h, l'.\ P(h::l')  \\
\forall x.\ x = c + 3& \textit{false} \\
\forall x.\ x \neq 0 \Rightarrow P(x)& \forall x'.\ P(\holtxt{SUC}(x'))
\end{array}\]

\subsubsection{Quantifier Heuristic Parameters for Tuples}

For tuples the situation is peculiar, because each quantifier over a variable of a product type
can be instantiated. The challenge is to decide which quantifiers should be instantiated and
which new variable names to use for the components of the pair.
There is a quantifier heuristic parameter called \holtxt{pair\_default\_qp}. It first looks for
subterms of the form $(\lambda (x_1, \ldots, x_n).\ \ldots)\ x$. If such a term is found $x$ is instantiated with
$(x_1, \ldots, x_n)$. Otherwise, subterms of the form $\holtxt{FST}(x)$ and $\holtxt{SND}(x)$ are searched. If such a term
is found, $x$ is instantiated as well. This parameter therefore allows simplifications like:
%
\[\begin{array}{r@{\quad \Longleftrightarrow \quad}l}
\forall p.\ (x = \holtxt{SND}(p)) \Rightarrow P(p)& \forall p_1.\ P(p_1, x) \\
\exists p.\ (\lambda (p_a, p_b, p_c). P(p_a, p_b, p_c))\ p & \exists p_a, p_b, p_c.\ P(p_a, p_b, p_c)
\end{array}\]

\holtxt{pair\_default\_qp} is implemented in terms of the more general
quantifier heuristic parameter \holtxt{pair\_qp}, which allows the
user to provide a list of ML functions. These functions get the
variable and the term. If they return a tuple of variables, these
variables are used for the instantiation, otherwise the next function
in the list is called or - if there is no function left - the variable
is not instantiated. In the example of $\exists p.\ (\lambda (p_a,
p_b, p_c). P(p_a, p_b, p_c))\ p$ these functions are given the
variable $p$ and the term $(\lambda (p_a, p_b, p_c). P(p_a, p_b,
p_c))\ p$ and return $\holtxt{SOME} (p_a, p_b, p_c)$.  This simple
ML-interface gives the user full control over what quantifier over
product types to expand and how to name the new variables.

\subsubsection{Quantifier Heuristic Parameter for Records}

Records are similar to pairs, because they can always be instantiated. Here, it is interesting that the necessary
monochotomy lemma comes from HOL~4's \holtxt{Type\_Base} library. This means that \holtxt{record\_qp} is stateful.
If a new record type is defined, the automatically proven monochotomy lemma is then automatically used
by \holtxt{record\_qp}. In contrast to the pair parameter, the one for records gets only one function instead of a
list of functions to decide which variables to instantiate. However, this function is simpler, because it just needs
to return true or false. The names of the new variables are constructed from the field-names of the record.
The quantifier heuristic parameter \holtxt{default\_record\_qp} expands all records.

\subsubsection{Stateful Quantifier Heuristic Parameters}

The parameter for records is stateful, as it uses knowledge from
\holtxt{Type\_Base}. Such information is not only useful for records
but for general datatypes. The quantifier heuristic parameter
\holtxt{TypeBase\_qp} uses automatically proven theorems about new
datatypes to exploit mono- and dichotomies. Moreover, there is also a
stateful \holtxt{pure\_stateful\_qp} that allows the user to
explicitly add other parameters to it.  \holtxt{stateful\_qp} is a
combination of \holtxt{pure\_stateful\_qp} and \holtxt{TypeBase\_qp}.

\subsubsection{Standard Quantifier Heuristic Parameter}

The standard quantifier heuristic parameter \holtxt{std\_qp} combines
the parameters for lists, options, natural numbers, the default one
for pairs and the default one for records.

\subsection{User defined Quantifier Heuristic Parameters}\label{sec_qps_user}

The user is also able to define own parameters. There
is \holtxt{empty\_qp}, which does not contain any information. Several
parameters can be combined using
\holtxt{combine\_qps}. Together with the basic types of user defined
parameters that are explained below, these functions provide an
interface for user defined quantifier heuristic parameters.

\subsubsection{Rewrites / Conversions}

A very powerful, yet simple technique for teaching the guess search
about new constructs are rewrite rules. For example, the standard rules
for equations and basic logical operations
cannot generate guesses for the predicate \holtxt{IS\_SOME}. By
rewriting \holtxt{IS\_SOME(x)} to \holtxt{?x'. x =
SOME(x')}, however, these rules fire.

\holtxt{option\_qp} uses this rewrite to implement support for
\holtxt{IS\_SOME}. Similarly support for predicates like \holtxt{NULL} is
implemented using rewrites. Even adding
rewrites like $\textsf{append}(l_1, l_2) = [\,] \Longleftrightarrow (l_1 =
[\,]\ \wedge\ l_2 = [\,])$ for list-append turned out to be beneficial
in practice.
\bigskip

\holtxt{rewrite\_qp} allows to provide rewrites in the form of rewrite theorems.
For the example of \holtxt{IS\_SOME} this looks like:

\begin{session}
\begin{verbatim}
> val thm = QUANT_INSTANTIATE_CONV [] ``!x. IS_SOME x ==> P x``
Exception- UNCHANGED raised

> val IS_SOME_EXISTS = prove (``IS_SOME x = (?x'. x = SOME x')``,
   Cases_on `x` THEN SIMP_TAC std_ss []);
val IS_SOME_EXISTS = |- IS_SOME x <=> ?x'. x = SOME x': thm

> val thm = QUANT_INSTANTIATE_CONV [rewrite_qp[IS_SOME_EXISTS]]
    ``!x. IS_SOME x ==> P x``
val thm = |- (!x. IS_SOME x ==> P x) <=>
             !x'. IS_SOME (SOME x') ==> P (SOME x'): thm
\end{verbatim}
\end{session}

To clean up the result after instantiation, theorems used to rewrite the result after instantiation can be provided via
\holtxt{final\_rewrite\_qp}.
\begin{session}
\begin{verbatim}
> val thm = QUANT_INSTANTIATE_CONV [rewrite_qp[IS_SOME_EXISTS],
                                    final_rewrite_qp[option_CLAUSES]]
      ``!x. IS_SOME x ==> P x``
val thm = |- (!x. IS_SOME x ==> P x) <=> !x'. P (SOME x'): thm
\end{verbatim}
\end{session}

If rewrites are not enough, \holtxt{conv\_qp} can be used to add conversions:
\begin{session}
\begin{verbatim}
- val thm = QUANT_INSTANTIATE_CONV [] ``?x. (\y. y = 2) x``
Exception- UNCHANGED raised

- val thm = QUANT_INSTANTIATE_CONV [convs_qp[BETA_CONV]] ``?x. (\y. y = 2) x``
> val thm = |- (?x. (\y. y = 2) x) <=> T: thm
\end{verbatim}
\end{session}

\subsubsection{Strengthening / Weakening}

In rare cases, equivalences that can be used for rewrites are unavailable. There might be just implications that
can be used for strengthening or weakening. The function
\holtxt{imp\_qp} might be used to provide such implication.

\begin{session}
\begin{verbatim}
- val thm = QUANT_INSTANTIATE_CONV [list_qp] ``!l. 0 < LENGTH l ==> P l``
Exception- UNCHANGED raised

- val LENGTH_LESS_IMP = prove (``!l n. n < LENGTH l ==> l <> []``,
    Cases_on `l` THEN SIMP_TAC list_ss []);
> val LENGTH_LESS_IMP = |- !l n. n < LENGTH l ==> l <> []: thm

- val thm = QUANT_INSTANTIATE_CONV [imp_qp[LENGTH_LESS_IMP], list_qp]
    ``!l. 0 < LENGTH l ==> P l``
> val thm =
   |- (!l. 0 < LENGTH l ==> P l) <=>
      !l_t l_h. 0 < LENGTH (l_h::l_t) ==> P (l_h::l_t): thm

- val thm = SIMP_CONV (list_ss ++
              QUANT_INST_ss [imp_qp[LENGTH_LESS_IMP], list_qp]) []
              ``!l. SUC (SUC n) < LENGTH l ==> P l``
> val thm =
   |- (!l. SUC (SUC n) < LENGTH l ==> P l) <=>
      !l_h l_t_h l_t_t_t l_t_t_h. n < SUC (LENGTH l_t_t_t) ==>
                                  P (l_h::l_t_h::l_t_t_h::l_t_t_t): thm
\end{verbatim}
\end{session}

\subsubsection{Filtering}
Sometimes, one might want to avoid to instantiate certain quantifiers.
The function \holtxt{filter\_qp} allows to add ML-functions that filter the handled
quantifiers. These functions are given a variable $x$ and a term $P(x)$.
The tool only tries to instantiate $x$ in $P(x)$, if all filter functions
return \textit{true}.

\begin{session}
\begin{verbatim}
- val thm = QUANT_INSTANTIATE_CONV []
     ``?x y z. (x = 1) /\ (y = 2) /\ (z = 3) /\ P (x, y, z)``
> val thm = |- (?x y z. (x = 1) /\ (y = 2) /\ (z = 3) /\ P (x,y,z)) <=>
               P (1,2,3): thm

- val thm = QUANT_INSTANTIATE_CONV
     [filter_qp [fn v => fn t => (v = ``y:num``)]]
     ``?x y z. (x = 1) /\ (y = 2) /\ (z = 3) /\ P (x, y, z)``
> val thm = |- (?x y z. (x = 1) /\ (y = 2) /\ (z = 3) /\ P (x,y,z)) <=>
                ?x   z. (x = 1) /\            (z = 3) /\ P (x,2,z): thm
\end{verbatim}
\end{session}

\subsubsection{Satisfying and Contradicting Instantiations}

As the satisfy library demonstrates, it is often
useful to use unification and explicitly given theorems to
find instantiations. In addition to satisfying instantiations, the quantifier heuristics framework
is also able to use contradicting ones. The theorems used for finding instantiations usually come from
the context. However, \holtxt{instantiation\_qp} allows to add additional ones:

\begin{session}
\begin{verbatim}
> val thm = SIMP_CONV (std_ss++QUANT_INST_ss[]) []
    ``P n ==> ?m:num. n <= m /\ P m``
Exception- UNCHANGED raised

> val thm = SIMP_CONV (std_ss++
               QUANT_INST_ss[instantiation_qp[LESS_EQ_REFL]]) []
               ``P n ==> ?m:num. n <= m /\ P m``
> val thm = |- P n ==> ?m:num. n <= m /\ P m = T : thm
\end{verbatim}
\end{session}

\subsubsection{Di- and Monochotomies}

Dichotomies can be exploited for guess search.
\holtxt{distinct\_qp} provides an interface to add theorems
of the form $\forall x.\ c_1(x) \neq c_2(x)$.
\holtxt{cases\_qp} expects theorems of the form
$\forall x. \ (x = \exists \textit{fv}. c_1(\textit{fv}))\ \vee \ldots \vee (x = \exists \textit{fv}. c_n(\textit{fv}))$.
However, only theorems for $n = 2$ and $n = 1$ are used. All other cases are currently ignored.

\subsubsection{Oracle Guesses}

Sometimes, the user does not want to justify guesses. The tactic
\holtxt{QUANT\_TAC} is implemented using oracle guesses for example.
A simple interface to oracle guesses is provided by \holtxt{oracle\_qp}.
It expects a ML function that given a variable and a term returns
a pair of an instantiation and the free variables in this instantiation.

As an example, lets define a parameter that states that every list is non-empty:
\begin{verbatim}
   val dummy_list_qp = oracle_qp (fn v => fn t =>
     let
        val (v_name, v_list_ty) = dest_var v;
        val v_ty = listSyntax.dest_list_type v_list_ty;

        val x = mk_var (v_name ^ "_hd", v_ty);
        val xs = mk_var (v_name ^ "_tl", v_list_ty);
        val x_xs = listSyntax.mk_cons (x, xs)
     in
        SOME (x_xs, [x, xs])
     end)
\end{verbatim}

\noindent
Notice, that an option type is returned and that the function is
allowed to throw \holtxt{HOL\_ERR} exceptions.
With this definition, we get

\begin{session}
\begin{verbatim}
- NORE_QUANT_INSTANTIATE_CONSEQ_CONV [dummy_list_qp]
    CONSEQ_CONV_STRENGTHEN_direction ``?x:'a list y:'b. P (x, y)``
> val it = ?y x_hd x_tl. P (x_hd::x_tl,y)) ==> ?x y. P (x,y) : thm
\end{verbatim}
\end{session}

\subsubsection{Lifting Theorems}

The function \holtxt{inference\_qp} enables the
user to provide theorems that allow lifting guesses over
user defined connectives. As writing these lifting theorems requires
deep knowledge about guesses, it is not discussed here. Please have a
look at the detailed documentation of the quantifier heuristics library as
well as its sources. You might also want to contact
Thomas Tuerk (\url{tt291@cl.cam.ac.uk}).

\subsubsection{User defined Quantifier Heuristics}

At the lowest level, the tool searches guesses using ML-functions
called \emph{quantifier heuristics}. Slightly simplified, such a
quantifier heuristic gets a variable and a term and returns a set of
guesses for this variable and term. Heuristics allow full
flexibility. However, to write your own heuristics a lot of knowledge
about the ML-datastructures and auxiliary functions is
required. Therefore, no details are discussed here. Please have a look
at the source code and contact Thomas Tuerk
(\url{tt291@cl.cam.ac.uk}), if you have questions.
\holtxt{heuristics\_qp} and \holtxt{top\_heuristics\_qp} provide
interfaces to add user defined heuristics to a quantifier heuristics
parameter.

\index{quantHeuristicsLib|)}

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