\chapter{Numbers and Arithmetic}\label{refnums}
\index{Arbitrary precision arithmetic,}
\index{Precision,arbitrary}
\index{R\textsc{exx},arithmetic}
 \nr{} arithmetic attempts to carry out the usual operations
(including addition, subtraction, multiplication, and division) in as
"natural" a way as possible.
What this really means is that the rules followed are those that are
conventionally taught in schools and colleges.
However, it was found that unfortunately the rules used vary
considerably (indeed much more than generally appreciated) from person
to person and from application to application and in ways that are not
always predictable.
The \nr{} arithmetic described here is therefore a compromise which
(although not the simplest) should provide acceptable results in most
applications.
\section{Introduction}\label{arithintro}

\index{Numbers,}
Numbers can be expressed in \nr{} very flexibly (leading and trailing
blanks are permitted, exponential notation may be used) and follow
conventional syntax.
Some valid numbers are:
\begin{lstlisting}
     12          /* A whole number               */
   '-76'         /* A signed whole number        */
     12.76       /* Some decimal places          */
 ' +  0.003 '    /* Blanks around the sign, etc. */
     17.         /* Equal to 17                  */
      '.5'       /* Equal to 0.5                 */
     4E+9        /* Exponential notation         */
      0.73e-7    /* Exponential notation         */
\end{lstlisting}
\index{Exponential notation,}
(Exponential notation means that the number includes a sign and a power
of ten following an "\textbf{E}" that indicates how the decimal
point will be shifted.  Thus \textbf{4E+9} above is just a short way
of writing \textbf{4000000000}, and \textbf{0.73e-7} is short
for \textbf{0.000000073}.)
\index{Operators,arithmetic}
\index{Numbers,arithmetic on}
\index{Arithmetic,operators}
\index{Integer division,}
\index{Division,integer}
\index{Remainder operator,}
 The arithmetic operators include
addition (indicated by a "\textbf{+}"),
subtraction ("\textbf{-}"),
multiplication ("\textbf{*}"),
power ("\textbf{**}"), and
division ("\textbf{/}").
There are also two further division operators:
integer divide ("\textbf{\%}") which divides and returns the integer part, and
remainder ("\textbf{//}") which divides and returns the remainder.
Prefix plus ("\textbf{+}") and
prefix minus ("\textbf{-}") operators are also provided.
\index{Rounding,}
 When two numbers are combined by an operation, \nr{} uses a set of
rules to define what the result will be (and how the result is to be
represented as a character string).
These rules are defined in the next section, but in summary:
\begin{itemize}
\item Results will be calculated with up to some maximum number of
significant digits.
That is, if a result required more than 9 digits it would normally be
rounded to 9 digits.
For instance, the division of 2 by 3 would result in 0.666666667 (it
would require an infinite number of digits for perfect accuracy).

You can change the default of 9 significant digits by using the
\keyword{numeric digits} instruction.  This lets you calculate using
as many digits as you need - thousands, if necessary.
\item Except for the division and power operators, trailing zeros are
preserved (this is in contrast to most electronic calculators, which
remove all trailing zeros in the decimal part of results).
So, for example:
\begin{lstlisting}
2.40 + 2  =>  4.40
2.40 - 2  =>  0.40
2.40 * 2  =>  4.80
2.40 / 2  =>  1.2
\end{lstlisting}
This preservation of trailing zeros is desirable for most
calculations (and especially financial calculations).
 If necessary, trailing zeros may be easily removed with the
 \textbf{strip} method (see page \pageref{refstrip}) , or by division by 1.
\item A zero result is always expressed as the single
digit \textbf{'0'}.
\item
Exponential form is used for a result depending on its value and
the setting of \keyword{numeric digits} (the default is 9 digits).
If the number of places needed before the decimal point exceeds this
setting, or the absolute value of the number is less
than \textbf{0.000001}, then the number will be expressed in
exponential notation; thus
\begin{lstlisting}
1e+6 * 1e+6
\end{lstlisting}
results in "\textbf{1E+12}" instead of
"\textbf{1000000000000}", and
\begin{lstlisting}
1 / 3E+10
\end{lstlisting}
results in "\textbf{3.33333333E-11}" instead of
"\textbf{0.0000000000333333333}".
\item
Any mixture of Arabic numerals (0-9) and  Extra digits (see page \pageref{refsyms})
can be used for the digits in numbers used in calculations.  The results
are expressed using Arabic numerals.
\end{itemize}
\section{Definition}\label{arithdefinition}
 This definition describes arithmetic for \nr{} strings
(type \textbf{R\textsc{exx}}).
The arithmetic operations are identical to those defined in the ANSI
standard for R\textsc{exx}.
\index{ANSI standard,arithmetic definition}
\footnote{
American National Standard for Information Technology -
Programming Language REXX, X3.274-1996, American National
Standards Institute, New York, 1996.
}
\subsection{Numbers}\label{refdefnum}
\index{Numbers,definition}
 A \emph{number} in \nr{} is a character string that includes one or
more decimal digits, with an optional decimal point.
The decimal point may be embedded in the digits, or may be prefixed or
suffixed to them.
The group of digits (and optional point) thus constructed may have
leading or trailing blanks, and an optional sign ("\textbf{+}"
or "\textbf{-}") which must come before any digits or decimal
point.
The sign may also have leading or trailing blanks.
Thus:
\index{Numeric,part of a number}
\index{Digits,in numbers}
\begin{alltt}
sign    ::=  + | -
digit   ::=  0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
digits  ::=  digit [digit]...
numeric ::=  digits . [digits]
             | [.] digits
number  ::=  [blank]... [sign [blank]...]
             numeric [blank]...
\end{alltt}

\index{Extra digits,in numbers}
where if the implementation supports  extra digits (see page \pageref{refsyms})
these are also accepted as \emph{digit}s, providing that they
represent values in the range zero through nine.
In this case each extra digit is treated as though it were
the corresponding character in the range 0-9.
\index{Period,in numbers}
\index{. (period),in numbers}
 Note that a single period alone is not a valid number.
\subsection{Precision}\label{refndi2}
\index{Arithmetic,precision}
\index{Precision,of arithmetic}
\index{Significant digits, in arithmetic,}
\index{DIGITS,on NUMERIC instruction}
\index{NUMERIC,DIGITS}
 The maximum number of significant digits that can result from an
arithmetic operation is controlled by the \keyword{digits} keyword on the
 \keyword{numeric} instruction (see page \pageref{refnumeric}) :
\begin{alltt}
\keyword{numeric digits} [\emph{expression}];
\end{alltt}
The expression is evaluated and must result in a positive whole
number.
This defines the precision (number of significant digits) to which
arithmetic calculations will be carried out; results will be rounded to
that precision,
if necessary.
 If no expression is specified, then the default precision is used.
The default precision is 9, that is, all implementations must support
at least nine digits of precision.  An implementation-dependent maximum
(equal to or larger than 9) may apply: an attempt to exceed this will
cause execution of the instruction to terminate with an exception.
Thus if an algorithm is defined to use more than 9 digits then if
the \keyword{numeric digits} instruction succeeds then the computation
will proceed and produce identical results to any other implementation.
 Note that \keyword{numeric digits} may set values below the default of
nine.
Small values, however, should be used with care - the loss of
precision and rounding thus requested will affect all \nr{}
computations, including (for example) the computation of new values for
the control variable in loops.

In the remainder of this section, the notation \textbf{digits} refers
to the current setting of \keyword{numeric digits}.
This setting may also be referred to in expressions in programs by using
the \textbf{digits}  special word (see page \pageref{refspecial}) .
\subsection{Arithmetic operators}
\index{Operators,arithmetic}
\index{Numbers,arithmetic on}
\index{Arithmetic,operators}

\nr{} arithmetic is effected by the operators "\textbf{+}",
"\textbf{-}", "\textbf{*}", "\textbf{/}",
"\textbf{\%}", "\textbf{//}", and "\textbf{**}"
(add, subtract, multiply, divide, integer divide, remainder, and power)
which all act upon two terms, together with the prefix operators
"\textbf{+}" and "\textbf{-}" (plus and minus)
which both act on a single term.
The result of all these operations is a \nr{} string, of
type \textbf{R\textsc{exx}}.
This section describes the way in which these operations are carried
out.
 Before every arithmetic operation, the term or terms being operated
upon have any extra digits converted to the corresponding Arabic numeral
(the digits 0-9).  They then have leading zeros removed (noting the
position of any decimal point, and leaving just one zero if all the
digits in the number are zeros) and are then truncated
to \textbf{digits+1} significant digits
\footnote{
\index{Guard digit in arithmetic,}
That is, to the precision set by \keyword{numeric digits}, plus one extra
"guard" digit.
}
(if necessary) before being used in the computation.
The operation is then carried out under up to double that precision, as
described under the individual operations below.
When the operation is completed, the result is rounded if necessary to
the precision specified by the \keyword{numeric digits} instruction.
\index{Rounding,definition}
 Rounding is done in the "traditional" manner, in that the extra
(guard) digit is inspected and values of 5 through 9 are rounded up,
and values of 0 through 4 are rounded down.
\footnote{
\index{,}
Even/odd rounding would require the ability to calculate to arbitrary
precision (that is, to a precision not governed by the setting of
\keyword{numeric digits}) at any time and is therefore not the mechanism
defined for \nr{}.
}
 A conventional zero is supplied preceding a decimal point if
otherwise there would be no digit before it.  Trailing zeros are
retained for addition, subtraction, and multiplication, according to
the rules given below, except that a result of zero is always expressed
as the single character \textbf{'0'}.  For division, insignificant
trailing zeros are removed after rounding.

The  \textbf{format} method (see page \pageref{refformat})  is defined to allow a
number to be represented in a particular format if the standard result
provided by \nr{} does not meet requirements.
\subsection{Arithmetic operation rules - basic operators}\label{}
\index{Trailing zeros,}
\index{Arithmetic,operation rules}
 The basic operators (addition, subtraction, multiplication, and
division) operate on numbers as follows:
\begin{description}
\item[Addition and subtraction]
\index{Addition,definition}
\index{+ plus sign,addition operator}
\index{Subtraction,definition}
\index{- minus sign,subtraction operator}
\index{Prefix operators,arithmetic}

If either number is zero then the other number, rounded
to \textbf{digits} digits if necessary, is used as the result (with
sign adjustment as appropriate).
Otherwise, the two numbers are extended on the right and left as
necessary up to a total maximum of \textbf{digits+1} digits.

The number with smaller absolute value may therefore lose some or
all of its digits on the right.
\footnote{
In the example, the number \textbf{yy.yyyyy} would have three digits
truncated if \textbf{digits} were \textbf{5}.
}
The numbers are then added or subtracted as appropriate.  For example:
\begin{alltt}
xxxx.xxx + yy.yyyyy
\end{alltt}
becomes:
\begin{alltt}
  xxxx.xxx00
+ 00yy.yyyyy
------------
  zzzz.zzzzz
\end{alltt}
.sumadd
The result is then rounded to \textbf{digits} digits if necessary,
taking into account any extra (carry) digit on the left after an
addition, but otherwise counting from the position corresponding to the
most significant digit of the terms being added or subtracted.
Finally, any insignificant leading zeros are removed.
 The \emph{prefix operators} are evaluated using the same rules;
the operations "\textbf{+number}" and "\textbf{-number}"
are calculated as "\textbf{0+number}" and
"\textbf{0-number}", respectively.
\item[Multiplication]
\index{Multiplication,definition}
\index{* multiplication operator,}

The numbers are multiplied together ("long multiplication")
resulting in a number which may be as long as the sum of the lengths of
the two operands.  For example:
\begin{alltt}
xxx.xxx * yy.yyyyy
\end{alltt}
becomes:
\begin{alltt}
zzzzz.zzzzzzzz
\end{alltt}
and the result is then rounded to \textbf{digits} digits if
necessary, counting from the first significant digit of the result.
\item[Division]
\index{Division,definition}

For the division:
\begin{alltt}
yyy / xxxxx
\end{alltt}
the following steps are taken: first, the number
"\textbf{yyy}" is extended
with zeros on the right until it is larger than
the number "\textbf{xxxxx}" (with note being taken of the change
in the power of ten that this implies).  Thus in this example,
"\textbf{yyy}"
might become
"\textbf{yyy00}".
Traditional long division then takes place, which can be written:
\begin{alltt}
         zzzz
      .------
xxxxx | yyy00
\end{alltt}

The length of the result ("\textbf{zzzz}") is such that the
rightmost "\textbf{z}" will be at least as far right as the
rightmost digit of the (extended) "\textbf{y}" number in the
example.  During the division, the "\textbf{y}" number will be
extended further as necessary, and the "\textbf{z}" number
(which will not include any leading zeros) may increase up
to \textbf{digits+1} digits, at which point the division stops and the
result is rounded.
Following completion of the division (and rounding if necessary),
insignificant trailing zeros are removed.
\end{description}
 \textbf{Examples:}
\begin{alltt}
/* With 'numeric digits 5' */
12+7.00     ==  19.00
1.3-1.07    ==  0.23
1.3-2.07    ==  -0.77
1.20*3      ==  3.60
7*3         ==  21
0.9*0.8     ==  0.72
1/3         ==  0.33333
2/3         ==  0.66667
5/2         ==  2.5
1/10        ==  0.1
12/12       ==  1
8.0/2       ==  4
\end{alltt}
\textbf{Note: }With all the basic operators, the position of the decimal point
in the terms being operated upon is arbitrary.
The operations may be carried out as integer operations with the
exponent being calculated and applied afterwards.
Therefore the significant digits of a result are not in any way
dependent on the position of the decimal point in either of the terms
involved in the operation.
\subsection{Arithmetic operation rules - additional operators}
 The operation rules for the power ("\textbf{**}"),
integer division ("\textbf{\%}"), and remainder
("\textbf{//}") operators are as follows:
\begin{description}
\item[Power]\label{refpower}

\index{Exponentiation,definition}
\index{Power operator,definition}
The "\textbf{**}" (power) operator raises a number (on the
left of the operator) to a power (on the right of the operator).
The term on the right is rounded to \textbf{digits} digits (if
necessary), and must, after any rounding, be a whole number, which may
be positive, negative, or zero.
If negative, the absolute value of the power is used, and then the
result is inverted (divided into 1).

For calculating the power, the number is effectively multiplied by
itself for the number of times expressed by the power, and finally
trailing zeros are removed (as though the result were divided by one).
 In practice (see note below for the reasons), the power is
calculated by the process of left-to-right binary reduction.
For "\textbf{x**n}": "\textbf{n}" is converted to
binary, and a temporary accumulator is set to 1.
If "\textbf{n}" has the value 0 then the initial calculation is
complete.
Otherwise each bit (starting at the first non-zero bit) is inspected
from left to right.
If the current bit is 1 then the accumulator is multiplied by
"\textbf{x}".
If all bits have now been inspected then the initial calculation is
complete, otherwise the accumulator is squared by multiplication and the
next bit is inspected.
When the initial calculation is complete, the temporary result is
divided into 1 if the power was negative.

The multiplications and division are done under the normal
arithmetic operation rules, detailed earlier in this section, using a
precision of \textbf{digits+elength+1} digits.
Here, \textbf{elength} is the length in decimal digits of the integer
part of the whole number "\textbf{n}" (\emph{i.e.}, excluding any sign,
decimal part, decimal point, or insignificant leading zeros, as though
the operation \textbf{n\%1} had been carried out and any sign removed).
Finally, the result is rounded to \textbf{digits} digits, if
necessary, and insignificant trailing zeros are removed.
\item[Integer division]

\index{Integer division,definition}

The "\textbf{\%}" (integer divide) operator divides two numbers
and returns the integer part of the result.
The result returned is defined to be that which would result from
repeatedly subtracting the divisor from the dividend while the dividend
is larger than the divisor.  During this subtraction, the absolute
values of both the dividend and the divisor are used: the sign of the
final result is the same as that which would result if normal division
were used.
 The result returned will have no fractional part (that is, no
decimal point or zeros following it).
If the result cannot be expressed exactly within \textbf{digits}
digits, the operation is in error and will fail - that is, the
result cannot have more digits than the current setting of \keyword{numeric
digits}.
For example, \textbf{10000000000\%3} requires ten digits to express the
result exactly (\textbf{3333333333}) and would therefore fail
if \textbf{digits} were \textbf{9} or smaller.
\item[Remainder]

\index{Remainder operator,definition}
The "\textbf{//}" (remainder) operator will return the remainder
from integer division, and is defined
as being the residue of the dividend after the operation of calculating
integer division as just described.
The sign of the remainder, if non-zero, is the same as that of the
original dividend.
 This operation will fail under the same conditions as integer
division (that is, if integer division on the same two terms would
fail, the remainder cannot be calculated).
\end{description}
 \textbf{Examples:}
\begin{lstlisting}
/* Again with 'numeric digits 5' */
2**3        ==  8
2**-3       ==  0.125
1.7**8      ==  69.758
2\%3         ==  0
2.1//3      ==  2.1
10\%3        ==  3
10//3       ==  1
-10//3      ==  -1
10.2//1     ==  0.2
10//0.3     ==  0.1
3.6//1.3    ==  1.0
\end{lstlisting}
 \textbf{Notes:}
\begin{enumerate}
\item A particular algorithm for calculating powers is described, since
it is efficient (though not optimal) and considerably reduces the
number of actual multiplications performed.
It therefore gives better performance than the simpler definition of
repeated multiplication.
Since results could possibly differ from those of repeated
multiplication, the algorithm must be defined here so that different
implementations will give identical results for the same operation on
the same values.
Other algorithms for this (and other) operations may always be used, so
long as they give identical results to those described here.
\item The integer divide and remainder operators are defined so that they
may be calculated as a by-product of the standard division operation
(described above).  The division process is ended as soon as the
integer result is available; the residue of the dividend is the
remainder.
\end{enumerate}
\subsection{Numeric comparisons}\label{arithnumericcomparisons}
\index{Arithmetic,comparisons}
\index{Operators,comparative}
\index{Comparison,of numbers}
\index{Numbers,comparison of}
 Any of the  comparative operators (see page \pageref{refcomps})  may be used
for comparing numeric strings.
However, the strict comparisons (for example, "\textbf{==}" and
"\textbf{>{}>}") are not numeric comparative operators and should
not normally be used for comparing numbers, since they compare from left
to right and leading and trailing blanks (and leading zeros) are
significant for these operators.
 Numeric comparison, using the normal comparative operators, is
effected by subtracting the two numbers (calculating the difference) and
then comparing the result with \textbf{'0'} - that is, the
operation:
\begin{lstlisting}
A ? B
\end{lstlisting}
where "\textbf{?}" is any normal comparative operator, is
identical to:
\begin{lstlisting}
(A - B) ? '0'
\end{lstlisting}
It is therefore the \emph{difference} between two numbers, when
subtracted under \nr{} subtraction rules, that determines their equality.
\subsection{Exponential notation}
\index{Ten, powers of,}
\index{Pure numbers,}
 The definition of numbers  above (see page \pageref{refdefnum})
describes "pure" numbers, in the sense that the character strings
that describe numbers can be very long.
 \textbf{Examples:}
\begin{lstlisting}
say  10000000000 * 10000000000
/* would display: 100000000000000000000 */

say  0.00000000001 * 0.00000000001
/* would display: 0.0000000000000000000001 */
\end{lstlisting}
For both large and small numbers some form of exponential notation
is useful, both to make such long numbers more readable and to make
evaluation possible in extreme cases.  In addition, exponential notation
is used whenever the "pure" form would give misleading
information.  For example:
\begin{lstlisting}
numeric digits 5
say 54321*54321
\end{lstlisting}
would display "\textbf{2950800000}" if long form were to be
used.
This is misleading, as it appears that the result is an exact multiple
of 100000, and so \nr{} would express the result in exponential
notation, in this case "\textbf{2.9508E+9}".
\index{Numbers,definition}
\index{Mantissa of exponential numbers,}
\index{Significand of exponential numbers,}
\index{Numeric,part of a number}
\index{Powers of ten in numbers,}
\index{Exponential notation,definition}
\index{E-notation,definition}
 The definition of \emph{number} (see above) is therefore extended
by replacing the description of \textbf{numeric} by the following:
\begin{alltt}
mantissa ::=  digits . [digits]
              | [.] digits
numeric  ::=  mantissa [E sign digits]
\end{alltt}
In other words, the numeric part of a number may be followed by an
"\textbf{E}" (indicating an exponential part), a sign,
and an integer following the sign that represents a power of ten that is
to be applied.
The "\textbf{E}" may be in uppercase or lowercase.
Note that no blanks are permitted within this part of a number, but the
integer may have leading zeros.
 \textbf{Examples:}
\begin{alltt}
12E+11  =  1200000000000
12E-5   =  0.00012
 12e+4  =  120000
\end{alltt}
 All valid numbers may be used as data for arithmetic.  The results
of calculations will be returned in exponential form depending on the
setting of \keyword{numeric digits}.
If the number of places needed before the decimal point
exceeds \textbf{digits}, or if the absolute value of the result is
less than \textbf{0.000001}, then exponential form will be used.
The exponential form generated by \nr{} always has a sign following the
"\textbf{E}".
If the exponent is 0 then the exponential part is omitted - that
is, an exponential part of "\textbf{E+0}" will never be
generated.
 If the default format for a number is not satisfactory for a
particular application, then the \textbf{format} method may be used to
control its format.  Using this, numbers may be explicitly converted to
exponential form or even forced to be returned in "pure" form.
\index{Notation,scientific}
\index{Notation,engineering}
\index{Exponential notation,}
\index{E-notation,}
\index{Scientific notation,}
\index{Engineering notation,}
\index{FORM,option of NUMERIC instruction}
\index{NUMERIC,FORM}
\label{refnfo2}
 Different exponential notations may be selected with the
 \keyword{numeric form} instruction (see page \pageref{refnform}) .
This instruction allows the selection of either scientific or
engineering notation.
\emph{Scientific notation} adjusts the power of ten so there is a
single non-zero digit to the left of the decimal point.
\emph{Engineering notation} causes powers of ten to be expressed as a
multiple of three - the integer part may therefore range
from \textbf{1} through \textbf{999}.
 \textbf{Examples:}
\begin{lstlisting}
numeric form scientific
say 123.45 * 1e11
/* would display: 1.2345E+13 */

numeric form engineering
say 123.45  * 1e11
/* would display: 12.345E+12 */
\end{lstlisting}
 The default exponential notation is scientific.
\subsection{Whole numbers}\label{refwholed}
\index{Whole numbers,definition}
\index{DIGITS,effect on whole numbers}
 Within the set of numbers understood by \nr{} it is useful to
distinguish the subset defined as \emph{whole numbers}.

A \emph{whole number} in \nr{} is a number that has a decimal part
which is all zeros (or that has no decimal part).
\subsection{Numbers used directly by \nr{}}\label{refnumuse}
\index{Numbers,use of by \nr{}}
\index{Functions,numeric arguments of}
\index{Rounding,when numbers used}
\index{DIGITS,rounding when numbers used}
 As discussed above, the result of any arithmetic operation is
rounded (if necessary) according to the setting of \keyword{numeric digits}.
Similarly, when a number (which has not necessarily been involved in an
arithmetic operation) is used directly by \nr{} then the same rounding
is also applied, just as though the operation of adding the number
to \textbf{0} had been carried out.
After this operation, the integer part of the number must have no more
digits than the current setting of \keyword{numeric digits}.

In the following cases, the number used must be a whole number and
an implementation restriction on the largest number that can be used
may apply:
\begin{itemize}
\item positional patterns, including variable positional patterns,
in  parsing templates (see page \pageref{refparsing})
\item the power value (right hand operand) of the power operator (see page \pageref{refpower}).
\item the values of \emph{exprr} and \emph{exprf} (following the
\keyword{for} keyword) in the  \keyword{loop} instruction (see page \pageref{refloop})
\item the value of \emph{exprd} (following the \keyword{digits}
keyword) in the  \keyword{numeric} instruction (see page \pageref{refnumeric}) .
\end{itemize}
 \textbf{Implementation minimum:} A minimum length of 9 digits must
be supported for these uses of whole numbers by a \nr{} language
processor.
\subsection{Implementation independence}
\index{Arithmetic,implementation independence}
 The \nr{} arithmetic rules are defined in detail, so that when a
given program is run the results of all computations are sufficiently
defined that the same answer will result for all correct
implementations.  Differences due to the underlying machine
architecture will not affect computations.
 This contrasts with most other programming languages, and with
 binary arithmetic (see page \pageref{refbinary})  in \nr{}, where the
result obtained may depend on the implementation because the precision
and algorithms used by the language processor are defined by the
implementation rather than by the language.
\subsection{Exceptions and errors}
\index{Exceptions,during arithmetic}
\index{Errors during arithmetic,}
\index{Arithmetic,exceptions}
\index{Arithmetic,errors}
\index{Arithmetic,overflow}
\index{Arithmetic,underflow}
\index{Overflow, arithmetic,}
\index{Underflow, arithmetic,}
 The following exceptions and errors may be signalled during arithmetic:
\begin{itemize}
\item Divide exception
 This exception will be signalled if division by zero was attempted,
or if the integer result of an integer divide or remainder operation had
too many digits.
\item Overflow/Underflow exception
 This exception will be signalled if the exponential part of a result
(from an operation that is not an attempt to divide by zero) would
exceed the range that can be handled by the language processor, when the
result is formatted according to the current settings of \keyword{numeric
digits} and \keyword{numeric form}.
The language defines a minimum capability for the exponential part,
namely exponents whose absolute value is at least as large as the
largest number that can be expressed as an exact integer in default
precision.
Thus, since the default precision is nine, implementations must support
exponents in the range \textbf{-999999999}
through \textbf{999999999}.
\item Insufficient storage
 Storage is needed for calculations and intermediate results, and on
occasion an arithmetic operation may fail due to lack of storage.
This is considered an operating environment error as usual, rather
than an arithmetical exception.
\end{itemize}
 \emph{In the reference implementation, the exceptions and error types
used for these three cases
are \textbf{DivideException}, \textbf{ExponentOverflowException},
and \textbf{OutOfMemoryError}, respectively.}
\index{,}
\index{,}
\index{,}


\documentclass[main.tex]{subfiles}
\begin{document}

\marginpar{Monday\\ 2020-12-21, \\ compiled \\ \today}

Let us continue with gauge-invariant cosmological perturbations.
Let us now give a gauge-invariant definition for the matter velocity:
%
\begin{align} \label{eq:matter-velocity-gauge-invariant}
2 v _{s} = 2 v^{\parallel} + \chi^{\parallel, \prime}
\,,
\end{align}
%
where, as usual, by ``matter'' we mean anything which goes on the right-hand side of the Einstein equations, and \(s\) means ``scalar''.

This velocity is related to the amplitude of the \textbf{shear tensor} for the matter velocity: specifically, from the shear tensor \(\sigma_{\mu \nu }\) we can define the quantity \(\qty(\sigma^{ij} \sigma_{ij} /2 )^{1/2}\).

For the scalar part, we have (following the notation by Bardeen)
%
\begin{align}
\epsilon_m &= \delta \rho + \rho_0' \qty(v^{\parallel} + \omega^{\parallel} )  \\
\rho_0 &= \rho_0 (\eta )
\,.
\end{align}

Note that energy density perturbations themselves are not gauge invariant.
The quantity \(\epsilon _m\) corresponds to \(\delta \rho \) in the gauge where \(v^{\parallel} + \omega^{\parallel} = 0\), which means that we are selecting constant-\(\eta \) hypersurfaces which are orthogonal to the worldlines of the fluid: the fluid's rest frame.

The quantity \(v^{\parallel} + \omega^{\parallel}\) enters into the expression for \(T^{0}_{i}\), which describes the momentum flux of the fluid.
We also define
%
\begin{align}
2 E_g = 2 \delta \rho + \rho_0' \qty(2 \omega^{\parallel} - \chi^{\parallel, \prime})
\,,
\end{align}
%
which is also equal to \(\delta \rho \) in the gauge in which \(2 \omega^{\parallel} - \chi^{\parallel, \prime} = 0\), which is the zero-shear or Poisson gauge.

We can also construct one vector perturbation, since we start with two and remove one with the gauge degree of freedom described as \(d^{i}\):
%
\begin{align}
\Psi_i = \omega^{\perp}_i - \chi_i^{\perp, \prime}
\,.
\end{align}

This is related to the amplitude of the vector geometric component of the geometric shear \(\sigma_{\mu \nu }\).
This term describes frame-dragging effects.

The matter velocity can be described as
%
\begin{align}
V^{i}_{s} = v^{i}_{\perp} + \chi^{i, \prime}_{\perp}
\marginnote{Compare to \eqref{eq:matter-velocity-gauge-invariant}.}
\,.
\end{align}

Also, we can define
%
\begin{align}
V^{i}_{c} = v^{i}_{\perp} + \omega^{i}_{\perp}
\,.
\end{align}

This is related to the amplitude of the vorticity\footnote{Local angular velocity of fluid elements} tensor \(\omega_{\mu \nu }\) (and, specifically, the quantity \(\qty(\omega^{ij} \omega_{ij} / 2)^{1/2}\)).

As for tensor perturbation modes, linear tensor perturbations are automatically gauge-invariant (at linear order, at least):
%
\begin{align}
\chi^{T, \prime}_{ij} =
\chi^{T}_{ij}
\,.
\end{align}

\section{Perturbed Einstein Equations}

Let us write the equations of motion for these linear cosmological perturbations.
We start from the Einstein equations \(G_{\mu \nu } = 8 \pi G T_{\mu \nu }\), and the Bianchi identities \(T^{\mu \nu }_{; \nu } = 0\).
The Einstein tensor is defined as
%
\begin{align}
G_{\mu \nu } &= R_{\mu \nu } - \frac{1}{2} g_{\mu \nu } R  \\
R_{\mu \nu } &= R^{\alpha }_{\mu \alpha \nu }  \\
R^{\alpha }_{\mu \nu \beta }&\sim \pdv{\Gamma }{x} + \Gamma^2  \\
\Gamma^{\mu }_{\nu \rho } &\sim g^{-1} \pdv{g}{x}
\,.
\end{align}

We can compute the nonvanishing Christoffel symbols in the unperturbed case (see, for example, the notes for Theoretical Cosmology), and then the perturbations of these; note that the inverse of a perturbed metric can be computed by inverting the perturbation according to the flat metric only (see \cite[eq.\ 8.20]{tissinoGeneralRelativityExercises2020}):
%
\begin{align}
\delta \Gamma^{0}_{00} &= \psi '  \\
\delta \Gamma^{0}_{0i} &= \partial_{i} \psi + \frac{a'}{a} \partial_{i} \omega^{\parallel}  \\
\delta \Gamma^{i}_{00} &= \frac{a'}{a} \partial^{i} \omega^{\parallel} + \partial^{i} \omega^{\parallel, \prime} + \partial^{i} \psi  \\
\delta \Gamma^{0}_{ij} &= -2 \frac{a'}{a} \psi \delta_{ij} - \partial_{i} \partial_{j} \omega^{\parallel} - 2 \frac{a'}{a} \phi \delta_{ij}
- \phi ' \delta_{ij} + \frac{a'}{a} D_{ij} \chi^{\parallel} + \frac{1}{2} D_{ij} \chi^{\parallel, \prime}  \\
\delta \Gamma^{i}_{0j} &= - \phi \delta^{i}_{j} + \frac{1}{2} D^{i}_{j} \chi^{\parallel, \prime}  \\
\delta \Gamma^{i}_{jk} &= \dots
\,.
\end{align}

The spatial components of the metric can be written as
%
\begin{align}
g_{ij} = \underbrace{a^2(\eta ) \qty[1 - 2 \phi ] \delta_{ij}}_{a^2(\eta , \vec{x})} + \dots
\,,
\end{align}
%
where we can express
%
\begin{align}
a(\eta , \vec{x}) = a(\eta ) \qty(1 - \phi (\eta , \vec{x}))
\,,
\end{align}
%
therefore \(\delta a = - a \phi \), which means that
%
\begin{align}
\delta \qty( \frac{a^{\prime}}{a}) = - \phi '
\,.
\end{align}

The unperturbed Ricci tensor reads
%
\begin{align}
R_{00} &= - 3 \frac{a''}{a} + 3 \qty( \frac{a'}{a})^2  \\
R_{ij} &=  \qty[\frac{a''}{a} + \qty(\frac{a'}{a})^2] \delta_{ij}
\,.
\end{align}

Its perturbation is
%
\begin{align}
\delta R_{00} &= \frac{a'}{a} \nabla^2 \omega^{\parallel} + \nabla^2 \omega^{\parallel, \prime} + 3 \phi^{\parallel} + 3 \frac{a'}{a} \phi' + 3 \frac{a'}{a} \psi '  \\
\delta R_{0i} &= \frac{a'}{a} \partial_{i} \omega^{\parallel} + \qty(\frac{a'}{a})^2 \partial_{i} \omega^{\parallel} +2 \partial_{i} \phi' + 2 \frac{a'}{a} \partial_{i} \psi + \frac{1}{2} \partial_{k} D^{k}_i \qty(\chi_{\parallel})'  \\
\delta R_{ij} &= \dots
\,.
\end{align}

\todo[inline]{Copy full expressions from the notes.}

The Ricci scalar \(R\) is given by \(R = (6/a^2) (a' / a)\) in flat FRLW, while its perturbation is
%
\begin{align}
\delta R &= \frac{1}{a^2} \qty(- 6 \frac{a'}{a} \nabla^2\omega^{\parallel} - 2 \nabla^2 \omega^{\parallel, \prime} - 2 \nabla^2 \psi - 6 \phi^{\parallel} - 6 \frac{a'}{a} \psi' - 18 \frac{a'}{a} \phi ' - 12 \frac{a''}{a} \psi + 4 \nabla^2 \phi + \partial_{k} \partial^{i} D^{k}_{i} \chi^{\parallel})
\,.
\end{align}

This expression is fully general, in a specific gauge it can be significantly simplified.
The stress-energy tensor we will use is given by
%
\begin{align}
T_{\mu \nu } = \rho u_\mu u_\nu + p h_{\mu \nu } + \Pi_{\mu \nu }
\,,
\end{align}
%
where \(\Pi^{\mu }_{\mu } = \Pi_{\mu \nu } u^{\nu } = 0\). This allows us to account for imperfections in the fluid. The only nonvanishing components of \(\Pi \) are the spatial ones \(\Pi_{ij}\).
This is true in any frame.

We can write it as
%
\begin{align}
\Pi_{ij} = D_{ij} \Pi^{\parallel} + 2\Pi^{\perp}_{(i, j)} + \Pi^{T}_{ij}
\,,
\end{align}
%
where, as usual, \(D_{ij} = \partial_{i} \partial_{j} - (1/3) \delta_{ij} \nabla^2\).
The component
%
\begin{align}
- T^{0}_{0} &= \rho_{0} (\eta ) + \delta \rho (\eta , \vec{x})  \\
&= \rho_0 (\eta ) \qty(1 + \delta )
\,,
\end{align}
%
while
%
\begin{align}
p = p_0 (\eta ) \qty(1 + \Pi _L)
\,,
\end{align}
%
where \(\Pi _L = \delta p / p_0 (\eta )\). The \(L\) stands for ``longitudinal''.

The unperturbed spatial components of the stress-energy tensor read:
%
\begin{align}
T^{i}_{j} &= p_0 (\eta ) \qty[ \qty(1 + \Pi _L) \delta^{i}_{j} + \Pi_{T, j}^{i}]  \\
\Pi_{T, j}^{i} &= \eval{\frac{\Pi^{i}_{j}}{p_0 (\eta )}}_{\text{traceless}}
\,.
\end{align}

The perturbation reads
%
\begin{align}
\delta T^{0}_{i} = \qty(\rho_0 + p_0 ) \qty(v_i + \omega _i )
&
\text{or}
&
\delta T^{i}_{0} = - (\rho_0 + p_0 ) v^{i}
\,.
\end{align}

This is quite general: it is the density of the \(i\)-component of the fluid's momentum, or the flux of energy in the \(i\)-th direction.

The linearly perturbed \(00\) EFE for scalar perturbation (as they are decoupled from the vector and tensor ones) reads
%
\begin{align}
\frac{3 a'}{a} \qty(\hat{\phi}' + \frac{a'}{a} \psi ) - \nabla^2 \qty(\hat{\phi} + \frac{a'}{a} \sigma ) = - 4 \pi G a^2 \delta \rho
\,,
\end{align}
%
where \(\hat{\phi} = \phi + (1/6) \nabla^2 \chi^{\parallel}\) and \(\sigma = - \omega^{\parallel} + (1/2) \chi^{\parallel, \prime}\).

The \(0i\) equation is
%
\begin{align}
\hat{\phi}' + \frac{a'}{a} \psi = - 4 \pi G a^2 \qty(\rho_0 + p_0 )V
\,,
\end{align}
%
where \(V = v^{\parallel} + \omega^{\parallel}\).
These two are not really ``evolution'' equations, they should be interpreted as constraints (to relate with \(\delta T_{00} \) and \(\delta T_{0i}\)) for the evolution of the other components.
On the other hand, from the trace of the \(ij\) equations we find
%
\begin{align}
\hat{\phi}'' + 2 \frac{a'}{a} \hat{\phi}' + \frac{a'}{a} \psi +
\qty[2 \qty(\frac{a'}{a})' + \qty(\frac{a'}{a})^2] \psi
= 4 \pi G a^2 \qty(\Pi _L + \frac{2}{3} \nabla^2 \Pi _T)p_0
\,,
\end{align}
%
where the \(T\) in \(\Pi _T = \Pi^{\parallel} / p_0 (\eta )\) means ``traceless''.
From the traceless part of these equations we find
%
\begin{align}
\sigma ' + 2 \frac{a'}{a} \sigma + \hat{\phi} - \psi = 8 \pi G a^2 \Pi _T p_0
\,.
\end{align}

So far we have not chosen a gauge; let us now put ourselves in the Poisson gauge. Here,
%
\begin{align}
\omega^{\parallel} = 0 = \chi^{\parallel}
\,.
\end{align}

Then, \(\hat{\phi} = \phi = - \Phi _H\), and \(\psi = \Psi _A\).
Now \(\sigma = - \omega^{\parallel} + (1/2) \chi^{\parallel, \prime} = 0\).
Then, the equations reads
%
\begin{align}
\phi - \psi &= 8 \pi G a^2 \Pi_T p_0  \\
\Phi _H + \Psi _A  &= - 8 \pi G a^2 \Pi _T  p_0
\,.
\end{align}

If the anisotropic stress can be neglected, then \(\phi = \psi \); this is the case for CDM, not so for nonisotropic relativistic particles or modified gravity.
If this is the case, then we can write the evolution equation in a simpler way: \(\Pi _T\) vanishes, by definition \(\Pi _L p_0 = \delta p\), which we can split into
%
\begin{align}
\delta p = c_s^2 \delta \rho + \delta p _{\text{non-adiab}}
\,,
\end{align}
%
and considering only the adiabatic part we find
%
\begin{align}
\Phi _H'' + 3 \qty(1 + c_s^2) \frac{a'}{a} \Phi _H' +
\qty[2 \qty(\frac{a'}{a})' + \qty(1 + 3 c_s^2) \qty(\frac{a'}{a})^2
- c_s^2 \nabla^2] \Phi _H = 0
\,,
\end{align}
%
which is an isolated evolution equation for \(\Phi _H\), a wave-like propagation equation.

The Poisson gauge is the most Newton-like one: the evolution equation becomes
%
\begin{align}
- \nabla^2 \Phi _H &= 4 \pi G a^2 \underbrace{\qty(\delta \rho - \frac{3 a'}{a} (\rho_0 + p_0 )V )}_{\epsilon_{m}}
\marginnote{Inserting the \(0i\) equation into the \(00\) one.}
\\
&= 4 \pi G a^2\epsilon_m
\,,
\end{align}
%
a Poisson equation.

For the vector perturbation \(\Psi_i\), we find (from the \(0i\) equation)
%
\begin{align}
\nabla^2\Psi _i = 16 \pi G a^2 \qty(\rho_0 + p_0 ) V_{i, c}
\,,
\end{align}
%
while for the tensor perturbations, starting from the traceless part of the \(ij\) EFE, we get
%
\begin{align}
\chi_{ij}^{\prime \prime, T} + 2 \frac{a'}{a} \chi^{T, \prime}_{ij} - \nabla^2 \chi^{T}_{ij} = 16 \pi G a^2p_0 (\eta ) \Pi^{T}_{ij}
\,.
\end{align}

We should also perturb for the matter source of the equations: \(T^{\mu \nu }_{; \nu } =0 \).
The energy density continuity equation (\(\mu = 0\)) reads
%
\begin{align} \label{eq:energy-density-continuity-equation}
\delta \rho ' + \frac{3 a'}{a} \qty(\delta p + \delta \rho ) - 3 \qty(\rho_0 + p_0 )  \hat{\phi}' + \qty(\rho_0 + p_0 ) \nabla^2 \qty(V + \sigma ) &= 0
\,,
\end{align}
%
while for \(\mu = i\) we get
%
\begin{align}
V' + \qty(1 + 3 c_s^2) \frac{a'}{a} V + \psi + \frac{1}{(\rho_0 + p_0 )} \qty(\delta p + \frac{2}{3} p_0 \nabla^2 \Pi _T) &= 0
\,.
\end{align}

The curvature perturbation on uniform energy density hypersurfaces is
%
\begin{align}
\zeta = - \hat{\phi} - H \frac{ \delta \rho }{\dot{\rho}_0 } = - \hat{\phi} - \frac{a'}{a} \frac{ \delta \rho }{\rho_0 '}
\,,
\end{align}
%
where, as usual, \(\hat{\phi} = \phi + (1/6) \nabla^2 \chi^{\parallel}\).

In a uniform energy density gauge \(\zeta = - \hat{\phi}\); also in the flat gauge we have \(\hat{\phi} = 0\), which tells us that \(\zeta \) is an energy density perturbation.
On super-horizon scales and taking equation \eqref{eq:energy-density-continuity-equation} in the gauge where \(\delta \rho = 0\), the Laplacian in the energy density continuity equation can be taken to vanish (\(k \ll 1\)), and we can express it as
%
\begin{align}
\zeta ' = - \frac{a'}{a} \frac{ \delta p}{\rho_0 + p_0 }
\,,
\end{align}
%
but we must evaluate this in the uniform energy density gauge the adiabatic contribution to the pressure perturbation vanishes, therefore we are left with
%
\begin{align}
\zeta ' = - \frac{a'}{a} \frac{ \delta p _{\text{non-adiabatic}}}{\rho_0 + p_0 }
\,.
\end{align}

For single-field models of slow-roll inflation, we find that on super-horizon scales
%
\begin{align}
\delta p _{\text{non-adiabatic}} \propto \frac{k^2 \Phi _H}{a^2} \approx 0 \implies \zeta \approx \const
\,.
\end{align}

The continuity equation for vector perturbations reads
%
\begin{align}
\qty[(\rho_0 +p_0 ) V_{ic}]' + \frac{4 a'}{a} (\rho_0 + p_0 ) V_{ic}
= - \nabla_k \qty(\Pi^{\perp k}_{, i} + \Pi^{\perp, k}_{i})
\,.
\end{align}

By Kelvin's circulation theorem, vorticity is conserved along trajectories unless there are dissipative effects.
Then, the divergence on the right-hand side of this equation vanishes, therefore we can write the left-hand side as
%
\begin{align}
a^3 \qty(\rho_0 + p_0 ) V_{ic} a = \const
\,.
\end{align}

This amounts to a momentum times \(a\), so the equation represents the conservation of the intrinsic angular momentum.

\end{document}


\section{Universal Optimisations}
\label{sec:universal}

There are some optimisations that apply to \emph{all} solvers. These universal optimisations efficiently
try to reduce the overall complexity of a given parity game in order to reduce the effort spent by any solver.
Clearly, such optimisations have to ensure that a solution of the modified game can be effectively and
efficiently translated back into a valid solution of the original game.

In the following we describe optimisations that are implemented on top of every solving algrithm:
SCC decomposition, detection of special cases, and compression. The next section then describes a generic
algorithm that uses (some of -- depending on the configuration) these optimisations in order to call
a real solver on as few and little parts of a game as possible.

\subsection{SCC Decomposition}

Let $G = (V, V_0, V_1, E, \Omega)$ be a parity game. A \emph{strongly connected component} (SCC) is a non-empty set
$S \subseteq V$ with the property that every node in $S$ can reach every other node in $S$, i.e. $uE^*v$ for
all $u, v \in S$ (where $E^*$ denotes the transitive-reflexive closure of $E$). A strongly connected component
$S$ is \emph{proper} iff $uE^+v$ for all $u, v \in S$ (where $E^+$ denotes the transitive closure of $E$). In
other words: An SCC $S$ is proper iff $|S| > 1$ or $S = \{u\}$ and $uEu$.

\begin{theorem}[\cite{tarjan:146}]
Every parity game $G = (V,V_0,V_1,E,\Omega)$ can, in time $\mathcal{O}(|E|)$, be partitioned into SCCs
$S_0, ..., S_n$ with $V = \bigcup_{i \leq n} S_i$ and $S_i \cap S_j = \emptyset$ for all $i \not= j$.
\end{theorem}

Additionally there is a strict partial ordering $\rightarrow$ on these SCCs which is defined as follows:
\begin{displaymath}
S_i \rightarrow S_j \quad:\iff\quad i \not= j \wedge \exists u \in S_i,\, v \in S_j:\, uEv
\end{displaymath}
This strict partial ordering is generally known as the \emph{topology} of the SCC decomposition. An SCC $S$
is called \emph{final} w.r.t.\ $\to$ if there is no SCC $T$ s.t.\ $S \to T$. Note that every SCC topology
of a finite graph must have at least one final SCC.

SCC decomposition of parity games as a universal optimisation works as follows. First, the game is decomposed
into SCCs along with the computation of the strict partial ordering $\rightarrow$. Then, all final SCCs
with respect to $\rightarrow$ are solved by a parity game solver. Since these SCCs are not connected to any
other SCCs, all solutions obtained in this manner can be directly used as solutions in the global game.

Second, the attractors for both players with respect to the computed winning sets of all maximal solved SCCs
are computed and removed from the game. The remainder is still a game, but because of the removal some of the
original SCCs may not be SCCs anymore. All ``damaged'' ex-SCCs are again decomposed into SCCs and replaced by
the new respective decomposition.
%(Note: There is no need to actually replace the SCC in the data structure; it is more convenient to implement
% this by recursion).
In this way, the remaining decomposition can be used again to solve the rest of the game, again starting
with those SCCs that are now final.
%Note that it is convenient to automatically solve improper SCCs since otherwise they usually need to be
%treated differently than normal SCCs in the real solving algorithms.

%\subsection{Excision of Dominions}

%Although there is no obvious way to further reduce a parity game to smaller sub games that need to be solved,

With this SCC decomposition it is not necessary to require solvers to solve an entire SCC let alone an entire
game. Instead it suffices to have them solve at least a dominion for one of the players. Given an SCC $S$ and
two dominions $D_0, D_1 \subseteq S$ with $D_0 \subseteq W_0$ and $D_1 \subseteq W_1$, one simply computes the
attractors $A_i := \attr{}{i}{D_i}$ and considers the induced subgame $(S \setminus A_0) \setminus A_1$ which
can be recursively solved by decomposition into SCCs etc.

% The excision of dominions is particularly useful for algorithms using a certain heuristic to generate ``good''
% strategies or for algorithms trying to find small dominions locally; some solution algorithms of the following
% subsection will apply the dominion excision approach. Since the excision of a dominion possibly leads to a new
% subgame that can be optimised and decomposed again, this optimisation can be very powerful.\TODO{Sehr schwammiger
% Paragraph.}

\subsection{Detection of Special Cases}

There are certain kinds of special games that can be solved very efficiently by the following procedures.
W.l.o.g.\ we can assume games to be proper strongly connected components. Remember that SCCs which are not proper
consist of a single node $v$ only that does not have an edge back to itself. The winner of $v$ is the owner
iff there is a successor that he/she wins. Since all successors belong to topologically greater SCCs we can
assume them to be solved already, and thus, the winner of $v$ is easily determined.

\begin{itemize}
\item \emph{Self-cycle games}: Suppose there is a node $v$ such that $vEv$. Then there are two cases depending on
the node's owner $p$ and the parity of the node's priority. If $\Omega(v) \not\equiv_2 p$ then taking the edge
$(v,v)$ is always a bad choice for player $p$ and this edge can be removed from the game for as long as
totality is preserved. If $\Omega(v) \equiv_2 p$ then taking this edge is always good in the sense that
$\{v\}$ is a dominion for player $p$. Hence, its attractor can be removed as described above.

\item \emph{One-parity games}: If all nodes in a proper SCC have the same parity, the whole game is obviously won
by the corresponding player no matter which transition the player uses. Hence, a winning strategy can be found
by random choice.

\item \emph{One-player games}: A game $G$ is a one-player game for player $i$ iff for all $v \in V_{1 - i}$ we have
$|vE| = 1$. Such a one-player game that is an SCC can be solved using a simple fixed-point iteration.
%\begin{align*}
%E_0\,\, &:= E \\
%E_{j + 1} &:= \{(u, v) \mid uE_jv \vee \exists w:(uE_jw \wedge wE_jv \wedge \Omega(u) \geq \Omega(w) \wedge \Omega(u) \equiv_2 i )\} \\
%E'\,\, &:= \bigcup_{j \in \Nat} E_j
%\end{align*}
%Now the following holds:
Player $i$ wins the game iff there is a node $u$ with $\Omega(u) \equiv_2 i$ and $u$ is reachable from itself
on a path that does not contain a priority greater than $\Omega(u)$.
% As player $i$ wins the game iff there is a cycle in the game won by player $i$ the fixed point iteration
%simply computes which nodes having parity $i$ can reach itself without seeing a greater priority than their
%own. Thus, if $E'$ connects $i$-parity nodes with itself, there needs to be a cycle using that particular
%node being won by player $i$. The conversion also holds: If there is no $i$-parity node $u$ s.t. $uE'u$ then
%the whole SCC is won by player $1-i$.
If there is such a cycle won by player $i$ then the rest of the SCC lies in the attractor of the cycle (since
player $i$ is the only one to make choices); otherwise, if there is no cycle won by player $i$, the whole game
is won by player $1-i$.
\end{itemize}

\subsection{Priority Compression}

The complexity of a parity game rises with the number of different priorities in the game. This optimisation step
attempts to reduce this number. Note that it is not the actual values of priorities that determine the winner.
It is rather their \emph{parity} on the one hand and their \emph{ordering} on the other. For instance, if there are
two priorities $p_1 < p_2$ in a game with $p_1 \equiv_2 p_2$ but there is no $p'$ such that $p_1 < p' < p_2$ and
$p' \not\equiv_2 p_1$ then every occurrence of $p_2$ can be replaced by $p_1$.

In general, let $P = (p_0,\ldots,p_k)$ be the list of all the priorities occurring in a game $G = (V,V_0,V_1,E,\Omega)$
s.t.\ $p_{i-1} < p_i$ for all $0 \le i < k$. W.l.o.g.\ we assume $p_0$ to be even. If the least priority occurring in
$G$ is odd, then simply add $p_0 = 0$ to this list which does not affect the construction in any way. We will also
use $P$ to denote the \emph{set} of all elements in $P$.

Take a decomposition of $P$ into maximal sublists of elements with the same parity, i.e.\
\begin{displaymath}
P \enspace = \enspace (p_{0,0},\ldots,p_{0,m_0},p_{1,0},\ldots,p_{1,m_1},\ldots,p_{n,0},\ldots,p_{n,m_n})
\end{displaymath}
with $p_{i,j} \equiv_2 p_{i,j'}$ for all $0 \le i \le n$, $0 \le j < j' \le m_i$ and
$p_{i,m_i} \not\equiv_2 p_{i+1,0}$ for all $0 \le i < n$. This defines a partial mapping $\omega: \Nat \to \Nat$ as
\begin{displaymath}
\omega(p) \enspace = \enspace
\begin{cases}
i &, \mbox{if } p = p_{i,j} \mbox{ for some } j  \\
\mathrm{undefined} &, \mbox{otherwise}
\end{cases}
\end{displaymath}
Note the following facts about $\omega$:
\begin{itemize}
\item $\omega$ is defined on all priorities occurring in $G$;
\item $\omega$ is \emph{decreasing}: we have $\omega(p) \le p$ for all $p \in P$;
\item $\omega$ is \emph{monotone}: for all $p,p'$ with $p \le p'$ we have $\omega(p) \le \omega(p')$;
\item $\omega$ \emph{preserves parities}: we have $\omega(p) \equiv_2 p$ for all $p \in P$;
\item $\omega$ is \emph{dense}: for all $p,p' \in P$ with $\omega(p)+1 < \omega(p')$ there is a $p''$ with
$\omega(p) < \omega(p'') < \omega(p')$.
\end{itemize}
Now define another parity game $G' := (V,V_0,V_1,E,\Omega')$ with $\Omega'(v) := \omega(\Omega(v))$. I.e.\ $G'$
results from $G$ by reducing the priorities according to the function $\omega$. Then $G'$ is equivalent to $G$
in the sense that the players' winning regions coincide in the two games, and a winning strategy $\sigma$ for
some player $i$ in $G$ is also a winning strategy for him/her in $G'$ and vice-versa. This is guaranteed by the
properties of $\omega$ identified above: due to monotonicity and preservation of parities, the greatest priority
ocurring in an infinite play in $G$ is even iff it is even in the same play in $G'$. The property of being
decreasing guarantees that this should in general be an optimisation, and density says that $G'$ is optimal
w.r.t.\ this optimisation.

% \begin{lemma}
% Every parity game $G = (V,V_0,V_1,E,\Omega)$ induces an equivalent parity game $G' = (V,V_0,V_1,E,\Omega')$ where
% $\Omega'$ is inductively defined as follows:
% \begin{displaymath}
% \Omega'(v) \enspace := \enspace
% \begin{cases}
% m(v) \enspace, &\mbox{if } \Omega(v) \equiv_2 m(v) \\
% m(v) + 1 & \mbox{otherwise}
% \end{cases}
% \end{displaymath}
% and
% \begin{displaymath}
% m(v) \enspace := \enspace \max \{0, \Omega'(w) \mid \Omega(w) < \Omega(v)\}
% \end{displaymath}
% Then $W_0(G) = W_0(G')$, $W_1(G) = W_1(G')$ and every winning strategy for player $i \in \{0, 1\}$ w.r.t. $G$ is a winning strategy for player $i$ w.r.t. $G'$ and vice versa.
% \end{lemma}

% Since $\Omega(v) \leq \Omega(w)$ iff $\Omega'(v) \leq \Omega'(w)$ as well as $\Omega(v) \equiv_2 \Omega'(v)$ it is not hard to see that the greatest priority occurring infinitely often in a play w.r.t. $G$ has the same parity as w.r.t. $G'$.

\subsection{Priority Propagation}

Note that any play visiting a node $v$ has to -- due to totality -- also visit one of the successors of
$v$. Now suppose that the priorities of all successors of $v$ are greater than the priority of $v$ itself.
Then $v$'s priority is irrelevant in the sense that no play is won by either player because $v$'s priority
occurs in it. For those plays not visiting $v$ at all this is trivial and for those plays that do visit
$v$ this is simply because $v$ is certainly not the geatest priority occurring in this play, let alone
occurring infinitely often. Hence, $v$'s priority can be replaced by a greater one.

In general, let $G = (V,V_0,V_1,E,\Omega)$. Applying \emph{backwards propagation} in node $v$ results in
the game $G' = (V,V_0,V_1,E,\Omega')$ where
$\Omega' = \Omega[v \mapsto \max \{ \Omega(v), \min \{ \Omega(w) \mid w \in vE \} \}]$.
Similarly, \emph{forwards propagation} replaces $v$'s priority with the minimum of all
priorities of its predecessors if that is greater than its current priority. It is equally sound because
any play that visits $v$ infinitely often must visit one of its predecessors infinitely often too.

Both backwards and forwards propagation can be iterated and combined thus reducing the range of priorities
in a game.

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


\section{Representing endomorphisms with matrices}


\newpage{}

\hypertarget{a004---reducing-dispersion-by-assigning-a-concrete-value-per-word-and-learning-from-it}{%
\section{A004 - reducing dispersion by assigning a concrete value per
word and learning from
it}\label{a004---reducing-dispersion-by-assigning-a-concrete-value-per-word-and-learning-from-it}}

A001 collects as many different values for each word as it can get. When
estimating, it uses any of those values more or less randomly (of cause
smoothend by the fact that we take 100 random values and then only use a
value from a certain position representing the percentage of certainty
we want to have). Anyways, that hinders our ability to ``learn''.

The idea behind this algorithm is to assign just one value to each word.
This way, when we see our error margin we might design a little learning
algorithm.

For example: - create an average model - while the mean squared error is
higher than \ldots{} - create 10 mutation of that model, for example by
randomly adding or substracting 1/10th of the value to each weight of
each word. - calculate the mean squared error for each mutation - take
the model with the least mean squared error and repeat


\documentclass{article}
\usepackage{graphicx}
\usepackage{siunitx}
\usepackage{hyperref}
\usepackage{xcolor}
\large

\begin{document}

 \title{GST108 : Introduction to Quantitative Reasoning}

\author{Oghenemaro Egbodo}
\maketitle
\newpage
\tableofcontents
\centering
\newpage

\section{Introduction}
A logic gate is a building block of a digital circuit which is at the heart of any computer operation.
\\
\subsection{LOGIC GATES}
A logic gate is an idealized model of computation or physical electronic device implementing a Boolean function, a logical operation performed on one or more binary inputs that produces a single binary output.
\includegraphics{unknown.png}
\newpage
Behind every digital system is a logic gate.\\
\includegraphics{unknown.jpeg}
\newpage
Logic gates perform logical operations that take binary input (0s and 1s) and produce  a single binary output. They are used in most electronic device including.\\
\begin{table}[h!]
	\begin{center}
		\begin{tabular}{|l|c|c|}
			\hline
		 Smartphones & Tablets & Memory Devices\\
		 \hline
		 \includegraphics[width=0.2\linewidth]{Unknown-1.jpeg} & \includegraphics[width=0.2\linewidth]{Unknown-2.jpeg} & \includegraphics[width=0.2\linewidth]{Unknown-3.jpeg}\\
		 \hline
	\end{tabular}
\end{center}
\end{table}
\newpage
 Now think of a logic gate like a light switch, it is either in an ON or OFF position. Similarly, the input output terminals are always in one of two binary positions false(0) and true(1). Each gate has its own logic or set of rules that determines how it acts based on multiple inputs outlined in a truth table.
\newpage
Combining 10s, 1000s or millions of logic gates makes it possible for a computer to perform highly complex operations and tasks at ever increasing speeds.
\newpage
A gate is a basic electronic circuit which operates on one or more signals to produce an output signal.
Logic gates are digital circuits constructed from diodes, transistors, and resistors connected in such a way that the circuit output is the result of a basic logic operation \textbf{(OR, AND, NOT)} performed on the inputs.
\newpage
\section{TYPES OF LOGIC GATES}
Fundamental gates are \textbf{AND, OR} and \textbf{NOT}\\
\includegraphics[width=0.3\linewidth]{images.png}\\
Derived Gates are \textbf{NAND, NOR, XOR} and \textbf{XNOR} (derived from the fundamental gates)\\
Universal Gates are \textbf{NAND} and \textbf{NOR} gates (the fundamental logic gates can be realized through them).
\\
\newpage
\subsection{AND Gate}
The expression C = A X B reads as “C equals A AND B.“\\
The multiplication sign (X) stands for the AND operation, same for ordinary multiplication of 1s and 0s.\\
 \includegraphics[width=0.5\linewidth]{Picture 1.png} \\
The AND operation produces a true output (result of 1) only for the single case when all of the input variables are 1 and a false output (result of 0) where one or more inputs are 0.
\\
\begin{figure}[h!]
	\centering
	\includegraphics[width=0.5\linewidth]{Unknown-4}
\end{figure}
\newpage
\includegraphics[width=0.2\linewidth]{Picture 1-0.png} \includegraphics[width=0.2\linewidth]{Picture 1-1.png}\\
\includegraphics[width=0.2\linewidth]{Picture 1-2.png} \includegraphics[width=0.2\linewidth]{Picture 1-3.png}\\
\newpage
\subsection{OR Gate}
The expression C = A + B reads as “C equals A OR B". It is the inclusive “OR”
\\
The Addition (+) sign stands for the OR operation
\\
\includegraphics{Picture 2.png}\\
The OR operation produces a true output (result of 1) when any of the input variable is 1 and a false output (result of 0) only when all the input variables are 0.
\\
\includegraphics{images-1.png}
\newpage
\includegraphics[width=0.3\linewidth]{Picture 2-0.png} \includegraphics[width=0.3\linewidth]{Picture 2-1.png}\\
\includegraphics[width=0.3\linewidth]{Picture 2-2.png} \includegraphics[width=0.3\linewidth]{Picture 2-3.png}\\
\newpage
\subsection{NOT GATE}
The NOT gate is called a logical inverter.\\
It has only one input. It reverses the original input (A) to give an inverted output C.\\
C = NOT A or C = $\overline{A}$\\
\includegraphics{Picture 3.png}\\
\begin{figure}[h!]
	\centering
	\includegraphics[width=0.5\linewidth]{Unknown-3}
\end{figure}
\newpage
\includegraphics[width=0.3\linewidth]{Picture 4.png} \includegraphics[width=0.3\linewidth]{Picture 4-1.png}
\newpage
\subsection{NOR GATE}
The NOR (NOT OR) gate circuit is an inverter OR gate.\\
C=$\overline{(A+B)}$\\
Reads as C = NOT of A or B.\\
\includegraphics[width=0.3\linewidth]{Picture 5.png}\includegraphics[width=0.1\linewidth]{Picture 5.1.png}  \includegraphics[width=0.3\linewidth]{Picture 5.2.png}\\
\includegraphics[width=0.3\linewidth]{Unknown-4.png}
\newpage
\includegraphics[width=1.0\linewidth]{Picture 6}\\
\newpage

\subsection{NAND GATE}
The NAND (NOT AND) Gate is an inverted AND Gate.\\
C = $\overline{((A x B)}$\\
Reads as C = NOT of A AND B.\\
The NAND Gate gives a false output (result of 0) only when both inputs are true (1).\\
\includegraphics[width=0.3\linewidth]{Picture 7.png}\includegraphics[width=0.1\linewidth]{Picture 5.1.png}\includegraphics[width=0.3\linewidth]{Picture 7-1.png}\\
\includegraphics[width=0.5\linewidth]{Unknown-5.png}
\newpage
\includegraphics[width=1.0\linewidth]{Picture}
\newpage
\subsection{XOR GATE}
An XOR (exclusive OR) gate acts in the same way as the exclusive OR logical connector. \\
It gives a true output (result of 1) if one, and only one, of the inputs to the gate is true (1), i.e either or but not both.\\
c = A $\oplus$ B = A.$\overline{B}$ + $\overline{A}$.B\\
\includegraphics[width=0.4\linewidth]{8} \includegraphics[width=0.1\linewidth]{Picture 5.1.png} \includegraphics[width=0.4\linewidth]{9}\\
\includegraphics[width=0.5\linewidth]{Unknown-6.png}\\
\newpage
\subsection{XNOR GATE}
The XNOR (exclusive - NOR) gate is a combination XOR gate followed by an inverter. It is represented by the $\odot$\\
Its gives a  true output (1), if the inputs are the same, and a false output (0) if the inputs are different.\\
C=$\overline{A \oplus B}$ = $\overline{(\overline{A}.B + A.\overline{B})}$\\
\includegraphics[width=0.3\linewidth]{10}\includegraphics[width=0.1\linewidth]{Picture 5.1.png} \includegraphics[width=0.3\linewidth]{11.1}\\
\includegraphics[width=0.8\linewidth]{Unknown-7.png}\\
\newpage
\section{Logic Gates and their Truth Tables}
\includegraphics[width=1.0\linewidth]{11}
\newpage
\section{Summary}
Using different combination of logic gates, complex operations can be performed.\cite{grace2020} \\
With the Universal logic gates - NAND and NOR, any other gate can be built.\\
There is no limit to the number of gates that can be arranged together in a single device.\\
However, in practice, there is a limit to the number of gates that can be packed into a given physical space.
\\
Arrays of logic gates are found in digital integrated circuits.
\\
\newpage
\subsection{Summary contd.}
The logic gates are abstract representations of real electronic circuits.\cite{grace2021study}\\
In computers, Logic gates are built using transistors combined with other electrical components like resistors and diodes. \\
These electrical components are wired together in order to transform a particular input to give a desired output.\\
\href{https://www.youtube.com/watch?v=sTu3LwpF6XI&t=481s}{Making Logic Gates from Transistors\textbf{(click to watch)}}
\newpage
\section{QUIZ}
What is the output of an AND gate if the inputs are 1 and 0?
\\
Explain the difference between the AND gate and the OR gate.\\
What is the output of a NOT gate if the inputs is 0?\\
Which logic gate is this?
\includegraphics[width=0.1\linewidth]{12}\\
Which gate is also known as a logical converter?
\\
\newpage
\bibliographystyle{ieeetr}
\bibliography{daBib}
\newpage
\includegraphics[width=1.0\linewidth]{thanks}

\end{document}


%!TEX TX-program = xelatex
\documentclass{article}
\usepackage{allan-eason}

\usetikzlibrary{positioning}
\usetikzlibrary{svg.path}

\graphicspath{ {./images/}}

\newcommand{\Title}{\LaTeX\ Test File}
\newcommand{\Author}{Eason S.}

\title{\Title}
\author{\Author}
\date{\today}

\geometry{a4paper, scale=0.8}

\lhead{\Title}

\begin{document}

	\maketitle

	\section{Maxwell's Equations}

		\subsection{Integral Format}

			\defword{Maxwell's Equations} (in forms of \defword{Integral}):

			\begin{align}
				\oiint_{S} \vect{D} \cdot \diff \vect{S} = \sum q &= \int_V \rho \diff V,\\
				\oiint_{S} \vect{B} \cdot \diff \vect{S} &= 0,\\
				\oint_{L} \vect{H} \cdot \diff \vect{l} = I + I_{\diff} &= \int_{S} \vect{j} \cdot \diff \vect{S} + \int_{S} \frac{\partial \vect{D}}{\partial t} \cdot \diff \vect{S},\\
				\oint_{L} \vect{E} \cdot \diff \vect{l} = - \frac{\diff \varPhi}{\diff t} &= - \int_{S} \frac{\partial \vect{B}}{\partial t} \cdot \diff \vect{S}.
			\end{align}

			Here, (1) states for the \defword{Gauss Theorem} in an \defword{Electric Field}, while (2) states for the \defword{Gauss Theorem} in an \defword{Magnetic Field}. (3) states for the relationship between \defword{A Changing Electric Field} and a magnetic field, or \defword{Ampere's Circulation Theorem}. (4) states for the relationship between \defword{A Changing Magnetic Field} and a electric field, or \defword{Faraday's Theorem of induction}.

	\section{Partial Derivative}

		\subsection{Definition}

			Let \(t=f(x, y, \ldots)\), the \defword{Partial Derivative} of \(f\) towards \(x\) is

			\[
				f'_{x} = \partial_x f = D_x f = D_1 f = \frac{\partial}{\partial x} f = \frac{\partial f}{\partial x} = \lim_{\Delta x \rightarrow 0} \frac{f(x + \Delta x, y, \ldots) - f(x, y, \ldots)}{\Delta x}.
			\]

			Define vector \(\vect{a} = (x, y, \ldots), \vect{\hat{e}_x} = (1, 0, \ldots)\), therefore

			\[
				\frac{\partial}{\partial x} f = \lim_{x\rightarrow 0} \frac{f(\vect{a} + h \vect{e_x}) - f(\vect{a})}{h}.
			\]

		\subsection{Gradient}

			Define \defword{Gradient} as following:

			\[
				\Grad f(\vect{a}) = \nabla f(\vect{a}) = \left(\at{\frac{\partial f}{\partial x}}{\vect{a}}, \at{\frac{\partial f}{\partial y}}{\vect{a}}, \ldots\right).
			\]

			We usually deine Gradient as following in a 3-Dimensional Space:

			\[
				\Grad = \nabla = \left[\frac{\partial}{\partial x}\right]\vect{\hat{e}_x} + \left[\frac{\partial}{\partial y}\right]\vect{\hat{e}_y} + \left[\frac{\partial}{\partial z}\right]\vect{\hat{e}_z}.
			\]

		\subsection{Directional Derivative}

			Define the \defword{Directional Derivative} along vector \(\vect{v} = \left(v_1, v_2, \ldots\right)\),

			\[
				\nabla_{\vect{v}} f(\vect{a}) = \lim_{x \rightarrow 0} \frac{f(\vect{a} + h \vect{v}) - f(\vect{a})}{h}.
			\]

		\subsection{Laplace Operator}

			Define the \defword{Laplace Operator} as following:

			\[
				\Delta = \frac{\partial^2}{\partial x^2} + \frac{\partial^2}{\partial y^2} + \frac{\partial^2}{\partial z^2} = \nabla \cdot \nabla = \nabla^2.
			\]

		\subsection{Divergence}

			Define the \defword{Divergence} of a vector as following: (it outputs a value)

			\[
				\Div \vect{v} = \nabla \cdot \vect{v} = \left(\frac{\partial}{\partial x}, \frac{\partial}{\partial y}, \frac{\partial}{\partial z} \right) \cdot \left(v_x, v_y, v_z\right) = \frac{\partial v_x}{\partial x} + \frac{\partial v_y}{\partial y} + \frac{\partial v_z}{\partial z}.
			\]

\end{document}


\documentclass{article}

\usepackage{tabu}
\usepackage{pbox}
\usepackage[margin=1in]{geometry}
\usepackage{xcolor}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{setspace}
\usepackage{tikz}
\usepackage{circuitikz}

\frenchspacing
\setlength{\parskip}{1em}
\renewcommand{\arraystretch}{1.5}
\setlength\parindent{0pt}
\DeclareMathSizes{10}{12}{8}{6}

\begin{document}

\section{MOSFETs}

\textbf{Definitions:}

\vspace{-5mm}
\begin{itemize} \itemsep0pt
	\item \(k_n \equiv \mu_nC_{ox} \frac{W}{L}\), \(k_p \equiv \mu_pC_{ox} \frac{W}{L}\)
	\item \(k'_n \equiv \mu_nC_{ox}\), \(k'_p \equiv \mu_pC_{ox}\)
	\item \(V_{OV} \equiv V_{GS}-V_{th}\)
	\item \(V_A \equiv \frac{1}{\lambda}\)
	\item \(V'_A \equiv \frac{V_A}{L}\)
	\item \(g_m \equiv \frac{\partial i_D}{\partial v_{GS}} = \frac{i_d}{v_{gs}}\)
\end{itemize}

\textbf{Large signal characteristics, \(k=k_n\) or \(k_p\) as appropriate:}

\begin{tabu}{  l  X  X  }
	\hline
	Region & Condition & Properties \\ \hline
	Saturation & \(|V_{GS}| > |V_{th}| \bigwedge |V_{DS}| \geq |V_{OV}|\) &
	\pbox{10cm}{
		\vspace{1mm}
		\(\begin{aligned}
					I_D &= \frac{k}{2} V_{OV}^2 (1+\frac{V_{DS}}{V_A}) \\
					&\approx \frac{k}{2} V_{OV}^2
		\end{aligned}\)
	}\\

	Triode & \(|V_{GS}| > |V_{th}| \bigwedge |V_{DS}| \leq |V_{OV}|\) &
	\pbox{10cm}{ \(I_D = k(|V_{OV}|-\frac{1}{2}|V_{DS}|)|V_{DS}|\) } \\

	Cutoff & \(|V_{GS}| \leq |V_{th}|\) & \(I_D = 0\)\\
	\hline
\end{tabu}

For N-channel devices, all absolute value operations can be ignored.

\vspace{5mm}
\textbf{Small signal characteristics (saturation only):}

\begin{circuitikz}[american voltages] \draw
		(0,2) node[anchor=east]{G}
		to[short, o-] (1,2)
		to[open, v<=\(v_{gs}\)] (1,0)
		(1,0) -- (3,0)
		to[short, -o] (3,-1)
		node[anchor=east]{S}
		(3,2) to[american controlled current source, l_=\(g_mv_{gs}\), -*] (3,0)
		-- (5,0)
		to[R, l=\(r_o\), -*] (5,2)
		(3,2) -- (5,2)
		to[short, -o] (6,2)
		node[anchor=west]{D}
;
\end{circuitikz}

\vspace{-5mm}
\begin{itemize}
	\item \(g_m = \frac{2I_D}{V_{OV}} = k|V_{OV}| = \sqrt{2kI_D}\)
	\item \(r_o = \frac{V_A}{I_D}\)
\end{itemize}

\newpage
\section{BJTs}

\textbf{Definitions:}

\vspace{-5mm}
\begin{itemize} \itemsep0pt
	\item \(V_T \equiv \frac{kT}{q} \approx 25\text{mV}\)
	\item \(\alpha \equiv \frac{\beta}{\beta + 1}\)
	\item \(g_m \equiv \frac{\partial I_C}{\partial V_{BE}}\)
\end{itemize}

\textbf{Large signal characteristics:}

\begin{tabu}{  l  X  X  }
	\hline
	Region & Condition & Properties \\ \hline

	Saturation & Both junctions forward biased &
	\pbox{10cm}{
		\vspace{-5mm}
		\setstretch{1.2}
		\(|V_{BE}| \approx 0.7\text{V}\) \\
		\(|V_{CE}| \approx 0.2\text{V}\) \\
		\(|V_{BC}| \approx 0.5\text{V}\) \\
		\(I_C = \beta_{forced} I_B\)
	}
	\\[-13mm]

	Active & EB junction forward biased, CB junction reverse biased &
	\pbox{10cm}{
		\setstretch{1.3}
		\(\begin{aligned}
					I_C &= I_S e^{\frac{|V_{BE}|}{V_T}} (1 + \frac{V_{CE}}{V_A}) \\[-3mm]
						   &\approx I_S e^{\frac{|V_{BE}|}{V_T}}
		\end{aligned} \) \\
		\(I_C = \beta I_B\) \\
		\(I_E = \frac{I_C}{\alpha} = I_B + I_C\) \\
		\(|V_{BE}| \text{is effectively limited at around 0.7V}\)
	} \\[-5mm]

	Cutoff & Both junctions reverse biased & \(I_C = I_B = 0\) \\[1mm]
	\hline
\end{tabu}

A junction is considered forward biased if the voltage over it is greater than 0.4V. For NPN devices, all absolute value operations can be ignored.

\vspace{5mm}
\textbf{Small signal characteristics (active only):}

\begin{circuitikz}[american voltages] \draw
		(0,2) node[anchor=east]{B}
		to[short, o-] (1,2)
		to[R, l=\(r_\pi\), v<=\(v_{be}\)] (1,0)
		(1,0) -- (4,0)
		to[short, -o] (4,-1)
		node[anchor=east]{E}
		(4,2) to[american controlled current source, l_=\(g_mv_{be}\), -*] (4,0)
		-- (6,0)
		to[R, l=\(r_o\), -*] (6,2)
		(4,2) -- (6,2)
		to[short, -o] (7,2)
		node[anchor=west]{C}
;
\end{circuitikz}

\vspace{-5mm}
\begin{itemize}
	\item \(g_m = \frac{I_C}{V_T}\)
	\item \(r_{\pi} = \frac{\beta}{g_m} = \frac{V_T}{I_B}\)
	\item \(r_o = \frac{V_A}{I_C}\)
\end{itemize}

\end{document}


\section{Conclusion}

The main research question is whether Chinese stocks show a positive return-variance correlation.
We cannot claim that in general since, in all periods, more than half of the Chinese companies' leverage effect is insignificant, i.e.\ the posterior $\rho$'s 5\% to 95\% credible interval contains the 0.
On the other hand, we see that the Chinese market participants uniformly have weaker leverage effect than the German ones.
Moreover, sometimes they even have anti-leverage.

Examining further differences and similarities is most interesting with the global crisis of 2007 in mind.
We found proof for $\rho$ being shifted to the negative direction throughout the crisis.
Even though the negative shift is present unquestionably in both countries, the hectic changes of the leverage effect in China bring doubts about the importance of the crisis as a driving factor.

While $\rho$ behaves similarly in China and in Germany throughout the crisis, estimates of $\phi$ contrast the two countries at the same period.
When there is a trend in the volatility, i.e.\ it is not constant plus white noise, then there is high autocorrelation and persistence.
These trends exist in the German stocks' volatilities around the Subprime Crisis and the European Debt Crisis, so at those times $\phi$ is considerably larger than its prior.
On the contrary, this phenomenon is not present in China.

\subsection*{Future work}

While there are many possible explanations for the leverage effect, there is not any for the anti-leverage effect, to the best of our knowledge.
Unusual regulations are likely to be the main factor here, but a different investment culture is also a possible reason.
Either way, a microeconomics-based approach could be the key that models agents maximising utility in a well designed environment.

Finally, time-varying leverage effect models could be another direction for improvements.
Simple linear functions would not be sufficient to model the shifts in crises, probably a higher order polynomial that still avoids overfitting, or an ARCH process for $\rho$ would increase the predictive power.
We did not find such attempts in the literature.


\section{Realizability-Enforcing Limiter}
\label{sec:limiter}

Condition~2 of Theorem~\ref{the:realizableDGIMEX} requires that the polynomial approximation $\vect{\cM}_{h}=\vect{\cM}_{h}^{(j)}$ ($j\in\{0,\ldots,i-1\}$) is realizable in every point in the quadrature set $S=\cup_{k=1}^{d}\hat{\vect{S}}^{k}$.
Following Zhang \& Shu \cite{zhangShu_2010a} we use the limiter in \cite{liuOsher_1996} to enforce the bounds on the zeroth moment $\cJ$.
%The bound-preserving DG-IMEX method developed in previous sections is designed to preserve realizability of the cell averaged moments, i.e., $\vect{\cM}_{\bK}\in\cR$, provided sufficiently accurate quadratures are used to integrate integrals in the DG method, a CFL condition is satisfied, and that the polynomial approximation $\vect{\cM}_{h}$, at time $t^{n}$, is realizable in a set of quadrature points in each element $\bK$.
%We denote this quadrature set by $S=\cup_{k=1}^{d}\hat{\vect{S}}^{k}\subset\bK$.
%In the DG method, we use the limiter proposed by Zhang \& Shu \cite{zhangShu_2010a} for scalar conservation laws to enforce the bounds on the zeroth moment $\cJ$ (see also \cite{liuOsher_1996}).
We replace the polynomial $\cJ_{h}(\vect{x})$ with the limited polynomial
\begin{equation}
  \tilde{\cJ}_{h}(\vect{x})
  =\vartheta_{1}\,\cJ_{h}(\vect{x})+(1-\vartheta_{1})\,\cJ_{\bK},
  \label{eq:limitDensity}
\end{equation}
where the limiter parameter $\vartheta_{1}$ is given by
\begin{equation}
  \vartheta_{1}
  =\min\Big\{\,\Big|\f{M-\cJ_{\bK}}{M_{S}-\cJ_{\bK}}\Big|,\Big|\f{m-\cJ_{\bK}}{m_{S}-\cJ_{\bK}}\Big|,1\,\Big\},
\end{equation}
with $m=0$ and $M=1$, and
\begin{equation}
  M_{S}=\max_{\vect{x}\in S}\cJ_{h}(\vect{x})
  \quad\text{and}\quad
  m_{S}=\min_{\vect{x}\in S}\cJ_{h}(\vect{x}).
\end{equation}

In the next step, we ensure realizability of the moments by following the framework of \cite{zhangShu_2010b}, developed to ensure positivity of the pressure when solving the Euler equations of gas dynamics.
We let $\widetilde{\vect{\cM}}_{h}=\big(\tilde{\cJ}_{h},\vect{\cH}_{h}\big)^{T}$.
Then, if $\widetilde{\bcM}_{h}$ lies outside $\cR$ for any quadrature point $\vect{x}_{q}\in S$, i.e., $\gamma(\widetilde{\bcM}_{h})<0$, there exists an intersection point of the straight line, $\vect{s}_{q}(\psi)$, connecting $\vect{\cM}_{\bK}\in\cR$ and $\widetilde{\vect{\cM}}_{h}$ evaluated in the troubled quadrature point $\vect{x}_{q}$, denoted $\widetilde{\vect{\cM}}_{q}$, and the boundary of $\cR$.
This line is given by the convex combination
\begin{equation}
  \vect{s}_{q}(\psi)=\psi\,\widetilde{\vect{\cM}}_{q}+(1-\psi)\,\bcM_{\bK},
\end{equation}
where $\psi\in[0,1]$, and the intersection point $\psi_{q}$ is obtained by solving $\gamma(\bs_{q}(\psi))=0$ for $\psi$, using the bisection algorithm\footnote{In practice, $\psi$ needs not be accurate to many significant digits, and the bisection algorithm can be terminated after a few iterations.}.
We then replace the polynomial representation $\widetilde{\vect{\cM}}_{h}\to\widehat{\vect{\cM}}_{h}$, where
\begin{equation}
  \widehat{\vect{\cM}}_{h}(\vect{x})=\vartheta_{2}\,\widetilde{\vect{\cM}}_{h}(\vect{x})+(1-\vartheta_{2})\,\vect{\cM}_{\bK},
  \label{eq:limitMoments}
\end{equation}
and $\vartheta_{2}=\min_{q}\psi_{q}$ is the smallest $\psi$ obtained in the element by considering all the troubled quadrature points.
This limiter is conservative in the sense that it preserves the cell-average $\widehat{\vect{\cM}}_{\bK}=\widetilde{\vect{\cM}}_{\bK}=\vect{\cM}_{\bK}$.

The realizability-preserving property of the DG-IMEX scheme results from the following theorem.
\begin{theorem}
  Consider the IMEX scheme in Eqs.~\eqref{imexStages}-\eqref{eq:imexCorrection} applied to the DG discretization of the two-moment model in Eq.~\eqref{eq:semidiscreteDG}.
  Suppose that
  \begin{itemize}
    \item[1.] The conditions of Theorem~\ref{the:realizableDGIMEX} hold.
    \item[2.] With $\vect{\cM}_{\bK}^{(i)}\in\cR$, the limiter described above is invoked to enforce
    \begin{equation*}
      \vect{\cM}_{h}^{(i)}(\vect{x})\in\cR ~ \text{for all} ~ \vect{x} \in S.
    \end{equation*}
    \item[3.] The IMEX scheme is GSA.
  \end{itemize}
  Then $\vect{\bcM}_{\bK}^{n+1}\in\cR$.
  \label{the:realizableDGIMEX2}
\end{theorem}
\begin{proof}
  By Theorem~\ref{the:realizableDGIMEX} (with $i=1$), we have $\vect{\cM}_{\bK}^{(1)}\in\cR$.
  Application of the realizability-enforcing limiter gives $\vect{\cM}_{h}^{(1)}(\vect{x})\in\cR$ for all $\vect{x} \in S$.
  Repeated application of these steps give $\vect{\cM}_{h}^{(i)}(\vect{x})\in\cR$ for all $\vect{x} \in S$ and $i\in\{1,\ldots,s\}$.
  Since the IMEX scheme is GSA, $\tilde{\vect{\cM}}_{\bK}^{n+1}\in\cR$.
  Finally, $\vect{\bcM}_{\bK}^{n+1}\in\cR$ follows from Lemma~\ref{lem:imexCorrectionCellAverage}.
\end{proof}