    \title{(some) LaTeX environments \par for Jupyter notebook}\author{@jfbercher}

    \section{Introduction}\label{introduction}

    This extension for IPython 4.x or Jupyter enables to use some LaTeX
commands and environments in the notebook's markdown cells.
\begin{enumerate} \item \textbf{LaTeX commands and environments}
\begin{itemize} \item support for some LaTeX commands within
markdown cells, \emph{e.g.} \texttt{\textbackslash{}textit},
\texttt{\textbackslash{}textbf}, \texttt{\textbackslash{}underline},
\texttt{author}, \texttt{\textbackslash{}title}, LaTeX comments \item
support for \textbf{theorems-like environments}, support for labels and
\textbf{cross references} \item support for \textbf{lists}:
\emph{enumerate, itemize},\\
\item limited support for a \textbf{figure environment}, \item support
for an environment \emph{listing}, \item additional \emph{textboxa}
environment \end{itemize} \item \textbf{Citations and
bibliography} \begin{itemize} \item support for
\texttt{\textbackslash{}cite} with creation of a References section
\end{itemize} \item it is possible mix markdown and LaTeX
markup \item \textbf{Document-wide numbering of equations and
environments, support for \texttt{\textbackslash{}label} and
\texttt{\textbackslash{}ref}} \item \textbf{Configuration toolbar} \item
\textbf{LaTeX\_envs dropdown menu for a quick insertion of environments}
\item Support for \textbf{User \LaTeX definitions file} \item
Environments title/numbering can be customized by users in
\texttt{user\_envs.json} config file \item \textbf{Export to HTML and
LaTeX with a customized exporter} \item Styles can be customized in the
\texttt{latex\_env.css} stylesheet \end{enumerate}

A simple illustration is as follows: one can type the following in a
markdown cell

\begin{listing}
The dot-product is defined by equation (\ref{eq:dotp}) in theorem \ref{theo:dotp} just below:
\begin{theorem}[Dot Product] \label{theo:dotp}
Let $u$ and $v$ be two vectors of $\mathbb{R}^n$. The dot product can be expressed as
\begin{equation}
\label{eq:dotp}
u^Tv = |u||v| \cos \theta,
\end{equation}
where $\theta$ is the angle between $u$ and $v$ ...
\end{theorem}
\end{listing}

and have it rendered as

The dot-product is defined by equation (\ref{eq:dotp}) in theorem
\ref{theo:dotp} just below: \begin{theorem}[Dot Product]
\label{theo:dotp} Let \(u\) and \(v\) be two vectors of
\(\mathbb{R}^n\). The dot product can be expressed as

\begin{equation}
\label{eq:dotp}
u^Tv = |u||v| \cos \theta,
\end{equation}

where \(\theta\) is the angle between \(u\) and \(v\) \ldots{}
\end{theorem}

    \subsection{** What's new **}\label{whats-new}

\textbf{November 2, 2016} - version 1.3.1

\begin{itemize}
\tightlist
\item
  Support for \textbf{user environments configuration} file
  (\texttt{user\_envs.json} in nbextensions/latex\_envs directory). This
  file is included by the html export template.\\
\item
  Support for \textbf{book/report style numbering} of environments, e.g.
  ``Example 4.2'' is example 2 in section 4.
\item
  Support for \texttt{\textbackslash{}author},
  \texttt{\textbackslash{}title}, and \texttt{maketitle}. Author and
  title are saved in notebook metadata, used in html/latex exports. The
  maketitle command also formats a title in the LiveNotebook.\\
\item
  Added a Toogle menu in the config toolbar to:

  \begin{itemize}
  \tightlist
  \item
    toggle use of user's environments config file
  \item
    toggle \texttt{report-style} numbering
  \end{itemize}
\end{itemize}

\textbf{September 18, 2016} - version 1.3

\begin{itemize}
\tightlist
\item
  Support for \textbf{user personal LaTeX definitions} file
  (\texttt{latexdefs.tex} in current directory). This file is included
  by the html and latex export templates.\\
\item
  Style for nested enumerate environments added in
  \texttt{latex\_envs.css}
\item
  Added a Toogle menu in the config toolbar to:

  \begin{itemize}
  \tightlist
  \item
    toggle the display of the LaTeX\_envs dropdown menu,
  \item
    toggle the display of labels keys,
  \item
    toggle use of user's LaTeX definition file
  \end{itemize}
\item
  \textbf{Cross references now use the true environment number instead
  of the reference//label key}. \textbf{References are updated
  immediately}. This works \textbf{document wide} and works for pre and
  post references
\item
  Support for optional parameters in theorem-like environments
\item
  Support for spacings in textmode, eg \texttt{\textbackslash{}par},
  \texttt{\textbackslash{}vspace,\ \textbackslash{}hspace}
\item
  Support for LaTeX comments % in markdown cells
- Reworked
  loading and merging of system/document configuration parameters
\end{itemize}

\textbf{August 28, 2016} - version 1.2

\begin{itemize}
\item
  \textbf{Added support for nested environments of the same type}.
  Nesting environments of different type was already possible, but there
  was a limitation for nesting environments of the same kind; eg itemize
  in itemize in itemize. This was due to to the fact that regular
  expressions are not suited to recursivity. I have developped a series
  of functions that enable to extract nested environments and thus cope
  with such situations.
\item
  Corrected various issues, eg
  \href{https://github.com/ipython-contrib/jupyter_contrib_nbextensions/issues/731}{\#731},
  \href{https://github.com/ipython-contrib/jupyter_contrib_nbextensions/issues/720}{\#720}
  where the content of nested environments was incorrectly converted to
  markdown.
\item
  Completely reworked the configuration toolbar. Re-added tips.
\item
  Added a toggle-button for the LaTeX\_envs menu
\item
  Added system parameters that can be specified using the
  \href{https://github.com/Jupyter-contrib/jupyter_nbextensions_configurator/tree/master/src/jupyter_nbextensions_configurator/static/nbextensions_configurator}{nbextensions\_configurator}.
  Thus reworked the configuration loading/saving.
\item
  Reworked extension loading. It now detects if the notebook is fully
  loaded before loading itself.
\end{itemize}

\textbf{August 03, 2016} - version 1.13

\begin{itemize}
\item
  Added a template to also keep the toc2 features when exporting to
  html:

\begin{verbatim}
jupyter nbconvert --to html_toclenvs FILE.ipynb
\end{verbatim}
\item
  Added a dropdown menu that enables to insert all main LaTeX\_envs
  environments using a simple click. Two keybards shortcuts (Ctrl-E and
  Ctrl-I) for equations and itemize are also provided. More environments
  and shortcuts can be added in the file \texttt{envsLatex.js}.
\item
  Added a link in the general help menu that points to the
  documentation.
\end{itemize}

\textbf{July 27, 2016} - version 1.1

\begin{itemize}
\item
  In this version I have reworked \textbf{equation numbering}. In the
  previous version, I used a specialized counter and detected equations
  rendering for updating this counter. Meanwhile, this feature has been
  introduced in \texttt{MathJax} and now we rely on MathJax
  implementation. rendering is significantly faster. We still have keep
  the capability of displaying only equation labels (instead of
  numbers). The numbering is automatically updated and is document-wide.
\item
  I have completely reworked the \textbf{notebook conversion} to plain
  \LaTeX and html. We provide specialized exporters, pre and post
  processors, templates. We also added entry-points to simplify the
  conversion process. It is now as simple as

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{jupyter} \NormalTok{nbconvert --to html_with_lenvs FILE.ipynb}
\end{Highlighting}
\end{Shaded}

  to convert \texttt{FILE.ipynb} into html while keeping all the
  features of the \texttt{latex\_envs} notebook extension in the
  converted version.
\end{itemize}

    \section{Main features}\label{main-features}

\subsection{Implementation principle}\label{implementation-principle}

The main idea is to override the standard Markdown renderer in order to
add a \emph{small} parsing of LaTeX expressions and environments. This
heavily uses regular expressions. The LaTeX expression are then rendered
using an html version. For instance
\texttt{\textbackslash{}underline\ \{something\}} is rendered as
\texttt{\textless{}u\textgreater{}\ something\ \textless{}/u\textgreater{}},
that is \underline{something}. The environments are replaced by an html
tag with a class derived from the name of the environment. For example,
a \texttt{definition} denvronment will be replaced by an html rendering
corresponding to the class \texttt{latex\_definition}. The styles
associated with the different classes are specified in
\texttt{latex\_env.css}. These substitutions are implemented in
\texttt{thsInNb4.js}.

    \subsection{Support for simple LaTeX
commands}\label{support-for-simple-latex-commands}

    We also added some LaTeX commands (e.g. \texttt{\textbackslash{}textit},
\texttt{\textbackslash{}textbf}, \texttt{\textbackslash{}underline}) --
this is useful in the case of copy-paste from a LaTeX document. The
extension also supports some textmode spacings, namely
\texttt{\textbackslash{}par},
\texttt{\textbackslash{}vspace,\ \textbackslash{}hspace} as well as
\texttt{\textbackslash{}title}, \texttt{\textbackslash{}author},
\texttt{maketitle} and LaTeX comments \% in markdown cells. Labels and
cross-references are supported, including for equations.

    \subsection{Available environments}\label{available-environments}

    \begin{itemize}
\tightlist
\item
  \textbf{theorems-like environments}: \emph{property, theorem, lemma,
  corollary, proposition, definition,remark, problem, exercise,
  example},
\item
  \textbf{lists}: \emph{enumerate, itemize},\\
\item
  limited support for a \emph{figure} environment,
\item
  an environment \emph{listing},
\item
  \emph{textboxa}, wich is a \texttt{textbox} environment defined as a
  demonstration (see below).
\end{itemize}

More environments can be added easily in the user\_envs config file
\texttt{user\_envs.json} or directly in the javascript source file
\texttt{thmsInNb4.js}. The rendering is done according to the stylesheet
\texttt{latex\_env.css}, which can be customized.
\begin{remark} When exporting to html, the
\texttt{latex\_env.css} file honored is the file on the github CDN.
However, customized css can be added in a \texttt{custom.css} file that
must reside in the same directory as the notebook itself. The reason for
that is that the \texttt{css} file must be in the same directory as the
notebook file for inclusion, which means copying it in each working
directory. As the rendering of the html file obtained is done using the
original javascript code, the same is true for the source files;
therefore it is better to curstomize environments in
\texttt{user\_envs.json} which is taken into account when exporting to
html.\\
\end{remark}

    \subsection{Automatic numerotation, labels and
references}\label{automatic-numerotation-labels-and-references}

    Several counters for numerotation are implemented: counters for problem,
exercise, example, property, theorem, lemma, corollary, proposition,
definition, remark, and figure are available. Mathjax-equations with a
label are also numbered document-wide. An anchor is created for any
label which enables to links things within the document:
\texttt{\textbackslash{}label} and \texttt{\textbackslash{}ref} are both
supported. A limitation was that numbering was updated (incremented)
each time a cell is rendered. Document-wide automatic updating is
implemented since version 1.3. A toolbar button is provided to reset the
counters and refresh the rendering of the whole document (this is still
useful for citations and bibliography refresh).

    \label{example:mixing} A simple example is as follows, featuring
automatic numerotation, and the use of labels and references. Also note
that standard markdown can be present in the environment and is
interpreted. \emph{The rendering is done according to the stylesheet
\texttt{latex\_env.css}, which of course, can be customized to specific
uses and tastes}.

\begin{listing}
\begin{definition} \label{def:FT}
Let $x[n]$ be a sequence of length $N$. Then, its **Fourier transform** is given by
\begin{equation}
\label{eq:FT}
X[k]= \frac{1}{N} \sum_{n=0}^{N-1} x[n] e^{-j2\pi \frac{kn}{N}}
\end{equation}
\end{definition}
\end{listing}

\begin{definition} \label{def:FT} Let \(x[n]\) be a sequence of
length \(N\). Then, its \textbf{Fourier transform} is given by

\begin{equation}
\label{eq:FT2}
X[k]= \frac{1}{N} \sum_{n=0}^{N-1} x[n] e^{-j2\pi \frac{kn}{N}}
\end{equation}

\end{definition}

    It is now possible to refer to the definition and to the equation by
their labels, as in:

\begin{listing}
As an example of Definition \ref{def:FT}, consider the Fourier transform (\ref{eq:FT2}) of a pure cosine wave given by
$$
x[n]= \cos(2\pi k_0 n/N),
$$
where $k_0$ is an integer.
\end{listing}

    As an example of Definition \ref{def:FT}, consider the Fourier transform
(\ref{eq:FT2}) of a pure cosine wave given by \[
x[n]= \cos(2\pi k_0 n/N),
\] where \(k_0\) is an integer. Its Fourier transform is given by \[
X[k] = \frac{1}{2} \left( \delta[k-k_0] + \delta[k-k_0] \right),
\] modulo \(N\).

    \subsection{Bibliography}\label{bibliography}

    \subsubsection{Usage}\label{usage}

    It is possible to cite bibliographic references using the standard LaTeX
\texttt{\textbackslash{}cite} mechanism. The extension looks for the
references in a bibTeX file, by default \texttt{biblio.bib} in the same
directory as the notebook. The name of this file can be modified in the
configuration toolbar. It is then possible to cite works in the
notebook, e.g.

\begin{listing}
The main paper on IPython is definitively \cite{PER-GRA:2007}. Other interesting references are certainly \cite{mckinney2012python, rossant2013learning}. Interestingly, a presentation of the IPython notebook has also be published recently in Nature \cite{shen2014interactive}.
\end{listing}

The main paper on IPython is definitively \cite{PER-GRA:2007}. Other
interesting references are certainly
\cite{mckinney2012python, rossant2013learning}. Interestingly, a
presentation of the IPython notebook has also be published recently in
Nature \cite{shen2014interactive}.

    \subsubsection{Implementation}\label{implementation}

    The implemention uses several snippets from the nice
\href{https://bitbucket.org/ipre/calico/downloads/}{icalico-document-tools}
extension that also considers the rendering of citations in the
notebook. We also use a modified version of the
\href{https://code.google.com/p/bibtex-js/}{bibtex-js} parser for
reading the references in the bibTeX file. The different functions are
implemented in \texttt{bibInNb4.js}. The rendering of citations calls
can adopt three styles (Numbered, by key or apa-like) -- this can be
selected in the configuration toolbar. It is also possible to customize
the rendering of references in the reference list. A citation template
is provided in the beginning of file \texttt{latex\_envs.js}:

\begin{verbatim}
var cit_tpl = {
// feel free to add more types and customize the templates
    'INPROCEEDINGS': '%AUTHOR:InitialsGiven%, ``_%TITLE%_\'\', %BOOKTITLE%, %MONTH% %YEAR%.',
    ... etc
\end{verbatim}

The keys are the main types of documents, eg inproceedings, article,
inbook, etc. To each key is associated a string where the \%KEYWORDS\%
are the fields of the bibtex entry. The keywords are replaced by the
correponding bibtex entry value. The template string can formatted with
additional words and effects (markdown or LaTeX are commands are
supported)

    \subsection{Figure environment}\label{figure-environment}

    Finally, it is sometimes useful to integrate a figure within a markdown
cell. The standard markdown markup for that is
\texttt{!{[}link{]}(image)}, but a limitation is that the image can not
be resized, can not be referenced and is not numbered. Furthermore it
can be useful for re-using existing code. Threfore we have added a
limited support for the \texttt{figure} environment. This enables to do
something like

\begin{listing}
\begin{figure}
\centerline{\includegraphics[width=10cm]{example.png}}
\caption{\label{fig:example} This is an example of figure included using LaTeX commands.}
\end{figure}
\end{listing}

which renders as

\begin{figure}
\centerline{\includegraphics[width=10cm]{example.png}}
\caption{\label{fig:example} This is an example of figure included using LaTeX commands.}
\end{figure}

Of course, this Figure can now be referenced:

\begin{listing}
Figure \ref{fig:example} shows a second filter with input $X_2$, output $Y_2$  and an impulse response denoted as $h_2(n)$
\end{listing}

Figure \ref{fig:example} shows a second filter with input \(X_2\),
output \(Y_2\) and an impulse response denoted as \(h_2(n)\)

    \subsection{figcaption}\label{figcaption}

    For Python users, we have added in passing a simple function in the
\texttt{latex\_envs.py} library.

This function can be imported classically, eg
\texttt{from\ latex\_envs.latex\_envs\ import\ figcaption} (or
\texttt{from\ jupyter\_contrib\_nbextensions.nbconvert\_support.latex\_envs\ import\ figcaption}
if you installed from the jupyter\_contrib repo).

Then, this function enables to specify a caption and a label for the
next plot. In turn, when exporting to \LaTeX, the corresponding plot is
converted to a nice figure environement with a label and a caption.
%
\begin{lstlisting}
%matplotlib inline
import matplotlib.pyplot as plt
from jupyter_contrib_nbextensions.nbconvert_support.latex_envs import figcaption
from numpy import pi, sin, arange

plt.plot(sin(2*pi*0.01*arange(100)))
\end{lstlisting}%

    \begin{verbatim}
[<matplotlib.lines.Line2D at 0x7f8a1872ba20>]
    \end{verbatim}

\begin{figure}[H]
\centering
\includegraphics[width=0.6\linewidth]{latex_env_doc_files/latex_env_doc_23_2.png}
\caption{This is a nice sine wave}
\label{fig:mysin}
\end{figure}
%    { \hspace*{\fill} \\}

    \subsection{Other features}\label{other-features}

    \begin{itemize}
\item
  As shown in the examples, eg \ref{example:mixing} (or just below),
  \textbf{it is possible to mix LaTeX and markdown markup in
  environments}
\item
  Support for \textbf{line-comments}: lines beginning with a % will
  be masked when rendering
- Support for \textbf{linebreaks}:
  \texttt{\textbackslash{}par\_}, where \_ denotes any space, tab,
  linefeed, cr, is replaced by a linebreak
\item
  Environments can be nested. egg:

  \begin{listing}
  This is an example of nested environments, with equations inside\\
  \begin{proof} Demo
  % This is a comment
\begin{enumerate}
  \item $$ \left\{ p_1, p_2, p_3 \ldots p_n \right\} $$
  \item A **nested enumerate**
  \item second item
  \begin{enumerate}
  \item $ \left\{ p_1, p_2, p_3 \ldots p_n \right\} $
  \item And *another one*
  \item second item
  \begin{enumerate}
  \item $$ \left\{ p_1, p_2, p_3 \ldots p_n \right\} $$
  \item second item
  \end{enumerate}
  \end{enumerate}
  \end{enumerate}
  \end{proof}
  \end{listing}

  which results in
\end{itemize}

    This is an example of nested environments, with equations inside\\
\begin{proof} Demo % This is a
comment
\begin{enumerate} \item

\begin{equation}\label{eq:}
\left\{ p_1, p_2, p_3 \ldots p_n \right\}
\end{equation}

\[ \left\{ p_1, p_2, p_3 \ldots p_n \right\} \] \item A \textbf{nested
enumerate} \item second item \begin{enumerate} \item
\(\left\{ p_1, p_2, p_3 \ldots p_n \right\}\) \item And \emph{another
one} \item second item \begin{enumerate} \item
\[ \left\{ p_1, p_2, p_3 \ldots p_n \right\} \] \item second item
\end{enumerate} \end{enumerate} \end{enumerate}
\end{proof}

    \subsection{User interface}\label{user-interface}

    \subsubsection{Buttons on main toolbar}\label{buttons-on-main-toolbar}

    On the main toolbar, the extension provides three buttons
\includegraphics{main_toolbar.png} The first one can be used to refresh
the numerotation of equations and references in all the document. The
second one fires the reading of the bibliography bibtex file and creates
(or updates) the reference section. Finally the third one is a toogle
button that opens or closes the configuration toolbar.

    \subsubsection{Configuration toolbar}\label{configuration-toolbar}

    The configuration toolbar \includegraphics{config_toolbar.png} enables
to enter some configuration options for the extension.

First, the \texttt{LaTeX\textbackslash{}\_envs} title links to this
documentation. Then, the bibliography text input can be used to indicate
the name of the bibtex file. If this file is not found and the user
creates the reference section, then this section will indicate that the
file was not found. The \texttt{References} drop-down menu enables to
choose the type of reference calls. The Equations input box enables to
initiate numbering of equations at the given number (this may be useful
for complex documents in several files/parts). The \texttt{Equations}
drop-down menu let the user choose to number equation or to display
their label instead. The two next buttons enable to toogle display of
the LaTeX\_envs environments insertion menu or to toggle the displau of
LaTeX labels. Finally The \texttt{Toogles} dropdown menu enable to
toogle the state of several parameters. All these configuration options
are then stored in the notebook's metadata (and restored on reload).

    The \texttt{Toggles} dropdown menu \includegraphics{Toggles.png}

enables to toggle the state of several configuration options:

\begin{itemize}
\tightlist
\item
  display the \texttt{LaTeX\_envs} insertion menu or not,
\item
  show labels anchors,
\item
  use \LaTeX user own LaTeX defintions (loads \texttt{latexdefs.tex}
  file from current document directory),
\item
  load user's environments configuration (file \texttt{user\_envs.json}
  in \texttt{nbextensions/latex\_envs} directory),
\item
  select ``report style'' numbering of environments
\end{itemize}

    \subsection{\texorpdfstring{The \texttt{LaTeX\_envs} insertion
menu}{The LaTeX\_envs insertion menu}}\label{the-latexux5fenvs-insertion-menu}

The \texttt{LaTeX\_envs} insertion menu
\includegraphics{LaTeX_envs_menu.png} enables a quick insertion of LaTeX
environments, some with a keyboard shorcut (this can be customized in
\texttt{envsLatex.js}). Besides, selected text will be inserted in the
environment.

    \section{Conversion to LaTeX and
HTML}\label{conversion-to-latex-and-html}

    The extension works in the live-notebook. Since it relies on a bunch of
javascript, the notebook does not render as is in services such as
\texttt{nbviewer} or \texttt{github} viewer. Similarly,
\texttt{nbconvert} does not know of the LaTeX constructs which are used
here and therefore does not fully convert notebooks using this
extension.

Therefore, we provide specialized templates and exporters to achieve
these conversions.

    \subsection{Conversion to html}\label{conversion-to-html}

We provide a template \texttt{latex\_envs.tpl} and an exporter class
\texttt{LenvsHTMLExporter} (in library \texttt{latex\_envs.py}). Using
that class, conversion simply amounts to

\begin{verbatim}
jupyter nbconvert --to latex_envs.LenvsHTMLExporter FILE.ipynb
\end{verbatim}

A shortcut is also provided

\begin{verbatim}
jupyter nbconvert --to html_with_lenvs FILE.ipynb
\end{verbatim}

It should be noted that the rendering is done exactly in the same way as
in the livenotebook. Actually, it is the very same javascript which is
run in the html file. The javascript functions are available on the
extension github as well as in the
\texttt{jupyter\_notebook\_extensions} CDN, which means that the
rendering of the html files requires an internet connection (this is
also true for the rendering of equations with MathJax).

Another template \texttt{latex\_envs\_toc.tpl} is provided which enables
to also keep the toc2 features when exporting to html (\emph{it even
works if you do not have the \texttt{toc2} extension!}):

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{jupyter} \NormalTok{nbconvert --to html_with_toclenvs FILE.ipynb}
\end{Highlighting}
\end{Shaded}

\textbf{If you use the version included in the
jupyter\_notebook\_extensions collection}, the entry-points (conversion
shortcuts) are a little different: use instead

\begin{itemize}
\item
\begin{verbatim}
jupyter nbconvert --to html_lenvs FILE.ipynb
\end{verbatim}
\item
\begin{verbatim}
jupyter nbconvert --to html_toclenvs FILE.ipynb
\end{verbatim}
\end{itemize}

\subsection{Conversion to LaTeX}\label{conversion-to-latex}

We provide two templates \texttt{thmsInNb\_article.tplx} and
\texttt{thmsInNb\_report.tplx} for article and report styles
respectively. Anyway one can also use the standard article, report, book
templates provided with nbconvert. Simply, we have improved some of the
internals styles. More importantly, we provide an exporter class
\texttt{LenvsLatexExporter} (also in library \texttt{latex\_envs.py}).
Using that class, conversion simply amounts to

\begin{verbatim}
jupyter nbconvert --to latex_envs.LenvsLatexExporter FILE.ipynb
\end{verbatim}

A shortcut is also provided

\begin{verbatim}
jupyter nbconvert --to latex_with_lenvs FILE.ipynb
\end{verbatim}

In addition, we provide several further options:

\begin{itemize}
\tightlist
\item
  \textbf{removeHeaders}: Remove headers and footers, (default false)
\item
  \textbf{figcaptionProcess}: Process figcaptions, (default true)
\item
  \textbf{tocrefRemove} Remove tocs and ref sections, + some cleaning,
  (default true),
\end{itemize}

These options can be specified on the command line as, eg,

\begin{verbatim}
jupyter nbconvert --to latex_with_lenvs --LenvsLatexExporter.removeHeaders=True -- LenvsLatexExporter.tocrefRemove=False FILE.ipynb
\end{verbatim}

\textbf{If you use the version included in the
jupyter\_notebook\_extensions collection}, the entry-points (conversion
shortcuts) are a little different: use instead

\begin{verbatim}
jupyter nbconvert --to latex_lenvs FILE.ipynb
\end{verbatim}

    \begin{example} As for an example, the present document has
been converted using

\begin{verbatim}
jupyter nbconvert --to latex_with_lenvs --LenvsLatexExporter.removeHeaders=True latex_env_doc.ipynb
\end{verbatim}

Then the resulting file (without header/footer) has been included in the
main file \texttt{documentation.tex}, where some LaTeX definitions of
environments are done (namely listings, colors, etc) and compiled using

\begin{itemize}
\tightlist
\item
  \texttt{xelatex\ -interaction=nonstopmode\ documentation}
\item
  \texttt{bibTeX\ documentation}
\item
  \texttt{xelatex\ -interaction=nonstopmode\ documentation}
\end{itemize}

The output can be consulted \href{documentation.pdf}{here}.\\
\end{example}

    \section{Installation}\label{installation}

    The extension consists in a package that includes a javascript notebook
extension. Since Jupyter 4.2, this is the recommended way to distribute
nbextensions. The extension can be installed

\begin{itemize}
\tightlist
\item
  from the master version on the github repo (this will be always the
  most recent version)
\item
  via pip for the version hosted on Pypi
\item
  as part of the great
  \href{https://github.com/ipython-contrib/Jupyter-notebook-extensions}{Jupyter-notebook-extensions}
  collection. Follow the instructions there for installing. Once this is
  done, you can open a tab at
  \texttt{http://localhost:8888/nbextensions} to enable and configure
  the various extensions.
\end{itemize}

From the github repo or from Pypi,

\begin{itemize}
\tightlist
\item
  \textbf{step 1}: install the package

  \begin{itemize}
  \tightlist
  \item
    \texttt{pip3\ install\ https://github.com/jfbercher/jupyter\_latex\_envs/archive/master.zip\ {[}-\/-user{]}{[}-\/-upgrade{]}}
  \item
    { or}
    \texttt{pip3\ install\ jupyter\_latex\_envs\ {[}-\/-user{]}{[}-\/-upgrade{]}}
  \item
    { or} clone the repo and install
    \texttt{git\ clone\ https://github.com/jfbercher/jupyter\_latex\_envs.git\ \ \ \ python3\ setup.py\ install}
  \end{itemize}
\end{itemize}

With Jupyter \textgreater{}= 4.2,

\begin{itemize}
\item
  \textbf{step 2}: install the notebook extension

\begin{verbatim}
jupyter nbextension install --py latex_envs [--user]
\end{verbatim}
\item
  \textbf{step 3}: and enable it

\begin{verbatim}
jupyter nbextension enable latex_envs [--user] --py
\end{verbatim}
\end{itemize}

For Jupyter versions before 4.2, the situation is more tricky since you
will have to find the location of the source files (instructions from
@jcb91 found
\href{https://github.com/jcb91/jupyter_highlight_selected_word}{here}):
execute

\begin{verbatim}
python -c "import os.path as p; from jupyter_highlight_selected_word import __file__ as f, _jupyter_nbextension_paths as n; print(p.normpath(p.join(p.dirname(f), n()[0]['src'])))"
\end{verbatim}

Then, issue

\begin{verbatim}
jupyter nbextension install <output source directory>
jupyter nbextension enable latex_envs/latex_envs
\end{verbatim}

where \texttt{\textless{}output\ source\ directory\textgreater{}} is the
output of the python command.

    \section{Customization}\label{customization}

\subsection{Configuration parameters}\label{configuration-parameters}

Some configuration parameters can be specified system-wide, using the
\texttt{nbextension\_configurator}. For that, open a browser at
\url{http://localhost:8888/nbextensions/} -- the exact address may
change eg if you use jupyterhub or if you use a non standard port. You
will then be able to change default values for the boolean values -
LaTeX\_envs menu (insert environments) present - Label equation with
numbers (otherwise with their \label{} key) - Number environments as
section.num - Use customized environments as given in `user\_envs.json'
(in the extension directory) and enter a default filename for the bibtex
file (in document directory).

All these values can also be changed per documents and these values are
stored in the notebook's metadata.

\subsection{User environments
configuration}\label{user-environments-configuration}

Environments can be customized in the file \texttt{user\_envs.json},
located in the \texttt{nbextensions/latex\_envs} directory. It is even
possible to add \emph{new} environments. This file is read at startup
(or when using the corresponding toggle option in the \texttt{Toggles}
menu) and merged with the standard configuration. An example is provided
as \texttt{example\_user\_envs.json}. For each (new/modified)
environment, one has to provide (i) the name of the environment (ii) its
title (iii) the name of the associated counter for numbering it; eg

\begin{verbatim}
    "myenv": {
        "title": "MyEnv",
        "counterName": "example"
    },
\end{verbatim}

Available counters are problem, exercise, example, property, theorem,
lemma, corollary, proposition, definition, remark, and figure.

\subsection{Styling}\label{styling}

The document title and the document author (as specified by
\texttt{\textbackslash{}title} and \texttt{\textbackslash{}author} are
formatted using the \texttt{maketitle} command according to the
\texttt{.latex\_maintitle} and \texttt{.latex\_author} div styles.

Each environment is formatted according to the div style
\texttt{.latex\_environmentName}, e.g. \texttt{.latex\_theorem},
\texttt{.latex\_example}, etc. The titles of environments are formatted
with respect to \texttt{.latex\_title} and the optional parameter wrt
\texttt{.latex\_title\_opt}. Images are displayed using the style
specified by \texttt{.latex\_img} and thir caption using
\texttt{.caption}. Finally, enumerate environments are formatted
according to the \texttt{.enum} style. Similarly, itemize environments
are formatted using \texttt{.item} style.

These styles can be customized either in the \texttt{latex\_envs.css}
file, or better in a \texttt{custom.css} in the document directory.

    \section{Usage and further examples}\label{usage-and-further-examples}

    \subsection{First example (continued)}\label{first-example-continued}

    We continue the first example on fthe Fourier transform definition
\ref{def:FT} in order to show that, of course, we can illustrate things
using a simple code. Since the Fourier transform is an essential tool in
signal processing, We put this in evidence using the \texttt{textboxa}
environment -- which is defined here in the css, and that one should
define in the LaTeX counterpart:

\begin{listing}
\begin{textboxa}
The Fourier transform is an extremely useful tool to have in your toolbox!
\end{textboxa}
\end{listing}

    \begin{textboxa}
The Fourier transform is an extremely useful tool to have in your toolbox!
\end{textboxa}

    The Fourier transform of a pure cosine is given by \[
X[k] = \frac{1}{2} \left( \delta[k-k_0] + \delta[k-k_0] \right),
\] modulo \(N\). This is illustrated in the following simple script:
%
\begin{lstlisting}
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from numpy.fft import fft
k0=4; N=128; n=np.arange(N); k=np.arange(N)
x=np.sin(2*np.pi*k0*n/N)
X=fft(x)
plt.stem(k,np.abs(X))
plt.xlim([0, 20])
plt.title("Fourier transform of a cosine")
_=plt.xlabel("Frequency index (k)")
\end{lstlisting}%
    \begin{center}
    \adjustimage{max size={0.6\linewidth}{0.6\paperheight}}{latex_env_doc_files/latex_env_doc_46_0.png}
    \end{center}
%    { \hspace*{\fill} \\}

    \subsection{Second example}\label{second-example}

    This example shows a series of environments, with different facets;
\textbf{links, references, markdown or/and LaTeX formatting within
environments}. The listing of environments below is typed using the
environment \emph{listing}\ldots{}

    \begin{listing}
\begin{definition} \label{def:diffeq}
We call \textbf{difference equation} an equation of the form
$$
\label{eq:diffeq}
y[n]= \sum_{k=1}^{p} a_k y[n-k] + \sum_{i=0}^q b_i x[n-i]
$$
\end{definition}

\begin{property}
If all the $a_k$ in equation (\ref{eq:diffeq}) of definition \ref{def:diffeq} are zero, then the filter has a **finite impulse response**.
\end{property}

\begin{proof}
Let $\delta[n]$ denote the Dirac impulse. Take $x[n]=\delta[n]$ in (\ref{eq:diffeq}). This yields, by definition, the impulse response:
$$
\label{eq:fir}
h[n]= \sum_{i=0}^q b_i \delta[n-i],
$$
which has finite support.
\end{proof}

\begin{theorem}
The poles of a causal stable filter are located within the unit circle in the complex plane.
\end{theorem}

\begin{example} \label{ex:IIR1}
Consider $y[n]= a y[n-1] +  x[n]$. The pole of the transfer function is $z=a$. The impulse response $h[n]=a^n$ has infinite support.
\end{example}

In the following exercise, you will check that the filter is stable iff $a$<1.

\begin{exercise}\label{ex:exofilter}
Consider the filter defined in Example \ref{ex:IIR1}. Using the **function** `lfilter` of scipy, compute and plot the impulse response for several values of $a$.
\end{exercise}

\end{listing}

    The lines above are rendered as follows (of course everything can be
tailored in the stylesheet): %
\begin{definition}
\label{def:diffeq} We call \textbf{difference equation} an equation of
the form

\begin{equation}
\label{eq:diffeq}
y[n]= \sum_{k=1}^{p} a_k y[n-k] + \sum_{i=0}^q b_i x[n-i]
\end{equation}

\end{definition} %
Properties of the filter are linked to
the coefficients of the difference equation. For instance, an immediate
property is %
% this is a comment
\begin{property}
If all the \(a_k\) in equation (\ref{eq:diffeq}) of definition
\ref{def:diffeq} are zero, then the filter has a \textbf{finite impulse
response}. \end{property} %
\begin{proof} Let
\(\delta[n]\) denote the Dirac impulse. Take \(x[n]=\delta[n]\) in
(\ref{eq:diffeq}). This yields, by definition, the impulse response:

\begin{equation}
\label{eq:fir}
h[n]= \sum_{i=0}^q b_i \delta[n-i],
\end{equation}

which has finite support. \end{proof}
%
\begin{theorem} The poles of a causal stable filter are
located within the unit circle in the complex plane.
\end{theorem} %
\begin{example} \label{ex:IIR1}
Consider \(y[n]= a y[n-1] + x[n]\). The pole of the transfer function is
\(z=a\). The impulse response \(h[n]=a^n\) has infinite support.
\end{example}

In the following exercise, you will check that the filter is stable iff
\(a\)\textless{}1. %
\begin{exercise}\label{ex:exofilter}
Consider the filter defined in Example \ref{ex:IIR1}. Using the
\textbf{function} \texttt{lfilter} of scipy, compute and plot the
impulse response for several values of \(a\). \end{exercise}

    \begin{listing}
The solution of exercise \ref{ex:exofilter}, which uses a difference equation as in Definition \ref{def:diffeq}:
\end{listing}

The solution of exercise \ref{ex:exofilter}, which uses a difference
equation as in Definition \ref{def:diffeq}:
%
\begin{lstlisting}
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import lfilter
d=np.zeros(100); d[0]=1 #dirac impulse
alist=[0.2, 0.8, 0.9, 0.95, 0.99, 0.999, 1.001, 1.01]
for a in alist:
    h=lfilter([1], [1, -a],d)
    _=plt.plot(h, label="a={}".format(a))
plt.ylim([0,1.5])
plt.xlabel('Time')
_=plt.legend()
\end{lstlisting}%
    \begin{center}
    \adjustimage{max size={0.6\linewidth}{0.6\paperheight}}{latex_env_doc_files/latex_env_doc_52_0.png}
    \end{center}
%    { \hspace*{\fill} \\}

    \subsection{Third example:}\label{third-example}

    This example shows that environments like itemize or enumerate are also
available. As already indicated, this is useful for copying text from a
TeX file. Following the same idea, text formating commands
\texttt{\textbackslash{}textit}, \texttt{\textbackslash{}textbf},
\texttt{\textbackslash{}underline}, etc are also available.

    \begin{listing}
The following \textit{environments} are available:
\begin{itemize}
    \item \textbf{Theorems and likes}
    \begin{enumerate}
        \item theorem,
        \item lemma,
        \item corollary
        \item ...
    \end{enumerate}
    \item \textbf{exercises}
    \begin{enumerate}
        \item problem,
        \item example,
        \item exercise
    \end{enumerate}
\end{itemize}
\end{listing}

    which gives\ldots{}

The following \textit{environments} are available:
\begin{itemize} \item \textbf{Theorems and likes}
\begin{enumerate} \item theorem, \item lemma, \item corollary \item
\ldots{} \end{enumerate} \item \textbf{exercises}
\begin{enumerate} \item problem, \item example, \item exercise
\end{enumerate} \end{itemize}

    \section{Disclaimer, sources and
thanks}\label{disclaimer-sources-and-thanks}

    Originally, I used a piece of code from the nice online markdown editor
\texttt{stackedit}
\url{https://github.com/benweet/stackedit/issues/187}, where the authors
also considered the problem of incorporating LaTeX markup in their
markdown.

I also studied and used examples and code from
\url{https://github.com/ipython-contrib/IPython-notebook-extensions}.

\begin{itemize}
\item
  This is done in the hope it can be useful. However there are many
  impovements possible, in the code and in the documentation.
  \textbf{Contributions will be welcome and deeply appreciated.}
\item
  If you have issues, please post an issue at
  \texttt{https://github.com/jfbercher/jupyter\_latex\_envs/issues}
  \href{https://github.com/jfbercher/jupyter_latex_envs/issues}{here}.
\end{itemize}

\textbf{Self-Promotion --} Like \texttt{latex\_envs}? Please star and
follow the
\href{https://github.com/jfbercher/jupyter_latex_envs}{repository} on
GitHub.


\documentclass[12pt]{article}
\usepackage[margin=1in]{geometry}
\usepackage[T1]{fontenc}
\usepackage[USenglish]{babel}
\usepackage[nodayofweek,level]{datetime}
\usepackage{amsfonts}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{tikz}
\usetikzlibrary{intersections,arrows.meta}
\usepackage{pgfplots}
\usepackage[scr]{rsfso}
\usepackage{array}
\usepackage{stackengine}
\stackMath

\usepackage{tikz,pgfplots}

\pgfplotsset{compat=1.10}
% Uncomment to use "fillbetween" function
% otherwise leave commented because
% the red highlighting is annoying
%\usepgfplotslibrary{fillbetween}

% Change for each new hw week
\newcommand{\dueDate}{\formatdate{13}{11}{2017}} % day/month/year
\newcommand{\hwNum}{6}

\begin{document}

\selectlanguage{USenglish}
%------------------------ Title Code ------------------------
\title{Homework: Week \hwNum}
\author{Joseph Ismailyan}
\date{}
\maketitle
\begin{flushleft}
Math 100 \\
Due: \dueDate \\
Professor Boltje \\
MWF 9:20a-10:25a
\end{flushleft}

%------------------------ Begin Page 1 ------------------------
\begin{minipage}[t]{0.40\textwidth}

\section*{Chapter 7}
\subsection*{10.}

\iffalse

\textbf{Proposition}:  \\If $ a\in \mathbb{Z} $, then $  a^3\equiv a\pmod{3}  $.
\newline\textit{Proof.} Suppose $ a\in \mathbb{Z} $. Consider $ (a-1)a(a+1) $. We can see that it is the product of three consecutive integers. It follows that \newline$ (a-1)a(a+1) =3!q, q\in \mathbb{Z}\newline =6q\newline=3(2q)\newline=3m, m=2q\in\mathbb{Z}.$ \newline Therefore $ 3|(a-1)a(a+1)\newline \rightarrow 3|(a^3-a)\rightarrow  a^3\equiv a\pmod{3}$.

\fi
\textbf{Proposition}:  \\If $ a\in \mathbb{Z} $, then $  a^3\equiv a\pmod{3}  $.
 Suppose $ a\in \mathbb{Z} $. Consider $ (a-1)a(a+1) $to be the product of three consecutive integers, so then the remainder when being divided by $ 3 $ must be either $ 0,1 \text{ or } 2 $. Then consider the first term of the series, $ a-1=3n \rightarrow 3|(a-1) $. Then the next in the series, $ a=3n $ so $ 3|a $. And lastly,  $ a-2=3n \rightarrow a=3n-2=3(n+1)-1 $ then for some integer $ m=n+1\in\mathbb{Z} \rightarrow a=3m-1\rightarrow a+1=3m$ so $ 3|(a+1) $. Therefore we can say that $ 3|(a-1)a(a+1) $ or just $ 3|(a^3-a) $ which implies $ a^3\equiv a\pmod{3} $.

\end{minipage}
% Creates verticle line
\hfill\vline\hfill
\begin{minipage}[t]{0.45\textwidth}

\subsection*{22.}
\textbf{Proposition}:  \\If $ n\in \mathbb{N} $, then $  4|n^2 $ or $ 4|(n^2-1)  $.
\newline\textit{Proof.} This proof requires two cases, one in which $ n $ is $ even $ and one in which $ n $ is $ odd $. Once both cases are proven, we can say that Case I is true or Case II is true, since every $ n $ in the set of natural numbers is either $ even $ or $ odd $.
\paragraph{} \textbf{Case I}
\newline
Suppose $ n $ is $ even $, therefore $ n=2k, n\in\mathbb{Z} $. Then $ n^2=(2k)^2=4k^2 $. We can then say $ n^2=4m,m=k^2\in\mathbb{Z} $ so $ 4|n^2 $.

\paragraph{} \textbf{Case II}
\newline
Suppose $ n $ is $ odd $, therefore $ n=2a+1, n\in\mathbb{Z} $. Then $ n^2=(2a+1)^2=4a^2+4a+1 $. We can then say $ n^2-1=4(a^2+a)=4b, b=(a^2+a)\in\mathbb{Z} $. Therefore $ 4|(n^2-1) $.

\end{minipage}
\pagebreak

%------------------------ End Page 1 ------------------------

%------------------------ Begin Page 2 ------------------------

\begin{minipage}[t]{0.40\textwidth}

\subsection*{26.}
\textbf{Proposition}:  \\The product of any $ n $ consecutive positive integers is divisible by $ n! $.
\newline\textit{Proof.} Suppose we write $ n $ consecutive positive integers as $ m,(m-1),(m-2),(m-3),...,(m-(n-1)) $. Then the product of these $ n $ consecutive positive integers would be $ m(m-1)(m-2)(m-3)...(m-(n-1))$. If we write $ \frac{m(m-1)(m-2)(m-3)...(m-(n-1))}{n!} $ then it is apparent that we have the number of ways to pick $ n $ items from a list of length $ m $. We can then multiply the expression by $ \frac{(m-n)!}{(m-n)!} $ then we get $ \frac{m(m-1)(m-2)(m-3)...(m-(n-1))(m-n)!}{n!(m-n)!} $ which can be simplified to $ \frac{m!}{(m-n)!n!} $. Recall that $ \frac{m!}{(m-n)!n!} $ is defined as $ {m}\choose{n} $ which yields an integer for all $ m\geq n $.

\subsection*{32.}
\textbf{Proposition}:  \\If $ n\in\mathbb{Z} $, then $ gcd(n,n+2)\in\{1,2\} $.
\newline\textit{Proof.} Suppose $ d=gcd(n,n+2) $, it follows that $ d|n $ and $ d|(n+2) $. So $ n=da, a\in\mathbb{Z} $ and $ n+2=dc, c\in\mathbb{Z} $. Then substituting $ n=da $ into $  n+2=dc $, we get $ da+2=dc\rightarrow 2=dc-da\rightarrow 2=d(c-a)=dm, m\in\mathbb{Z} $. Since $ 2=dm $, we know that $ d $ is a divisor of 2, and 2 has the divisors $ \pm1,\pm2 $. Since $ d $ is the \textbf{greatest} common divisor, then $ d=1 $ or $ d=2 $. Therefore $ d\in\{1,2\} $ and since $ d=gcd(n,n+2) $ then $ gcd(n,n+2)\in\{1,2\} $.

\end{minipage}
% Creates verticle line
\hfill\vline\hfill
\begin{minipage}[t]{0.45\textwidth}

\subsection*{32.}
\textbf{Proposition}:  \\If $ \text{gcd}(a,b)=\text{gcd}(b,c)=1 $, then $ \text{gcd}(ab,c)=1 $.
\newline\textit{Proof.} Suppose $ \text{gcd}(a,b)=\text{gcd}(b,c)=1 $. Then by \textbf{Proposition 7.1} we can say $ \text{gcd}(a,b)=ak+cl, k,l\in\mathbb{Z} $ and $ \text{gcd}(b,c)=bn+cm, n,m\in\mathbb{Z} $. Then $ ak=1-cl $ and $ bn=1-cm $. We can then multiply $ ak $ and $ bn $ which results in $ ab(kn)=(1-cl)(1-cm)=1-cm-cl-c^2lm $ Then $ 1=ab(kn)+c^2lm+cm+cl=ab(kn)+c(clm+m+l)\rightarrow 1=abx+cy, x=km\in\mathbb{Z},y=clm+l+m\in\mathbb{Z}  $. Since $ 1=abx+cy $, then $ \text{gcd}(ab,c)=1 $.

\subsection*{36.}
\textbf{Proposition}:  \\Suppose $ a,b\in\mathbb{N} $. Then $ a=\text{lcm}(a,b) $ if and only if $ b|a $.
\newline\textit{Proof.} Suppose $ a=\text{lcm}(a,b) $. By definition, this means $ b|a $ and $ a|a $.
Next, suppose $ b|a $. Then $ a=bn, n\in\mathbb{Z} $ and $ a=ad, d\in\mathbb{Z} $ then $ a\geq \text{lcm}(a,b) $. Then since $ a|\text{lcm}(a,b) $, we have $ \text{lcm}(a,b) =ac, c\in\mathbb{Z}$, which tells us $ a\leq \text{lcm}(a,b) $. Since  $ a\geq \text{lcm}(a,b) $ and $ a\leq \text{lcm}(a,b) $, we know that $ a= \text{lcm}(a,b) $.

\end{minipage}
\pagebreak

%------------------------ End Page 2 ------------------------

%------------------------ Begin Page 3 ------------------------

\begin{minipage}[t]{0.40\textwidth}

\section*{Chapter 8}
\subsection*{6.}
\textbf{Proposition}:  \\Suppose $ A,B $, and $ C $ are sets. Prove that if $ A\subseteq B $, then $ A-C\subseteq A-B $.
\newline\textit{Proof.} Suppose $ A,B $, and $ C $ are sets and $ A\subseteq B $. Then \\$ A-C=\{x:(x\in A)\land(x\not\in\ C)\} $. Since $ A\subseteq B $, then $ x\in B $. Then $ B-C=\{x:(x\in B)\land(x\not\in\ C)\} $. Since $ x\in A-C $ and $ x\in B-C $, then $ A-C\subseteq A-B $.

\subsection*{12.}
\textbf{Proposition}:  \\Suppose $ A,B $, and $ C $ are sets. then $ A-(B\cap C)=(A-B)\cup(A-C) $.
\newline\textit{Proof.} Consider $ A-(B\cap C)\\= \{x:(x\in A)\land(x\not\in(B\land C))\}\\=\{x:(x\in A)\land(x\not\in B\land x\not\in C))\}$\\By DeMorgan's Law\\$ \{x:((x\in A)\land (x\not\in B))\lor ((x\in A)\land (x\not\in C))\} $\\By Distributive Law\\ Since \\$ A-B=\{x:(x\in A)\land(x\not\in\ B)\} $\\and\\ $ A-C=\{x:(x\in A)\land(c\not\in\ C)\} $ then since $ (x\in A-B) \lor (x\in A-C)\\\rightarrow (A-B)\cup (A-C)$.

\end{minipage}
% Creates verticle line
\hfill\vline\hfill
\begin{minipage}[t]{0.45\textwidth}

\subsection*{22.}
\textbf{Proposition}:  \\Let $ A $ and $ B $ be sets. Prove that $ A\subseteq B $ if and only if $ A\cap B=A $.
\newline\textit{Proof.} Suppose $ A\cap B=A $. Let $ x\in A $ be an arbitrary element. Then since $ A\cap B=A $, we know $ x\in A\cap B $. So $ x\in B $, therefore $ A\subseteq B $.
\\Next suppose $ A\subseteq B $. If $ x\in A\cap B $, then $ x\in A $ so $ A\cap B\subseteq A $.
\\Finally, suppose $ A\subseteq B $. If $ x\in A $ then $ x\in B $, which implies $ x\subseteq A\cap B $. Therefore $ A\subseteq A\cap B $. Since $ A\cap B\subseteq A  $ and $ A\subseteq A\cap B $ then $ A\cap B=A $.

\subsection*{28.}
\textbf{Proposition}:  \\Prove $ \{12a+25b:a,b\in\mathbb{Z} \}=\mathbb{Z} $.
\newline\textit{Proof.} Suppose $ 12a+25b $. Since $ a,b\in\mathbb{Z} $,$  12a+25b\in\mathbb{Z}  $.
\\Next, suppose the set $ X=\{12a+25b:a,b\in\mathbb{Z} \}$, the set $ Y=\mathbb{Z} $, and $ y\in Y $. Then consider $ 12(-2)+25(1)=1 $ where $ a=-2 $ and $ b=1 $. Then we can multiply the equation by $ y $ and get $ 12(-2y)+25(y)=y $, where $ a=-2y $  and  $ b=y $. Then $ y\in Y $ implies $ y\in X $, therefore $ Y\subseteq X $. So $ \{12a+25b:a,b\in\mathbb{Z} \}=\mathbb{Z} $.

\end{minipage}
\pagebreak

%------------------------ End Page 4 ------------------------

\end{document}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Short Sectioned Assignment
% LaTeX Template
% Version 1.0 (5/5/12)
%
% This template has been downloaded from:
% http://www.LaTeXTemplates.com
%
% Original author:
% Frits Wenneker (http://www.howtotex.com)
%
% License:
% CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%----------------------------------------------------------------------------------------
%	PACKAGES AND OTHER DOCUMENT CONFIGURATIONS
%----------------------------------------------------------------------------------------

\documentclass[paper=a4, fontsize=11pt]{scrartcl} % A4 paper and 11pt font size

\usepackage[colorlinks=true, allcolors=red]{hyperref}
\usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs
%\usepackage{fourier} % Use the Adobe Utopia font for the document - comment this line to return to the LaTeX default
\usepackage[english]{babel} % English language/hyphenation
\usepackage{amsmath,amsfonts,amsthm} % Math packages

\usepackage{sectsty} % Allows customizing section commands
% \allsectionsfont{\centering \normalfont\scshape} % Make all sections centered, the default font and small caps

\usepackage{tikz}
\usetikzlibrary{automata,positioning}

\usepackage{fancyhdr} % Custom headers and footers
\pagestyle{fancyplain} % Makes all pages in the document conform to the custom headers and footers
\fancyhead{} % No page header - if you want one, create it in the same way as the footers below
\fancyfoot[L]{} % Empty left footer
\fancyfoot[C]{} % Empty center footer
\fancyfoot[R]{\thepage} % Page numbering for right footer
\renewcommand{\headrulewidth}{0pt} % Remove header underlines
\renewcommand{\footrulewidth}{0pt} % Remove footer underlines
\setlength{\headheight}{13.6pt} % Customize the height of the header

\numberwithin{equation}{section} % Number equations within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)
\numberwithin{figure}{section} % Number figures within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)
\numberwithin{table}{section} % Number tables within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)

\setlength\parindent{0pt} % Removes all indentation from paragraphs - comment this line for an assignment with lots of text

\usepackage{mathtools}
\DeclarePairedDelimiter{\ceil}{\lceil}{\rceil}
\DeclarePairedDelimiter{\floor}{\lfloor}{\rfloor}

\newcommand{\heads}{\textsc{h}}
\newcommand{\tails}{\textsc{t}}

\newcommand{\logten}{\log}%\mathrm{log}\hspace{0.05in}}
\newcommand{\logtwo}{\lg}%\mathrm{lg}\hspace{0.05in}}
\newcommand{\loge}{\ln}%\mathrm{ln}\hspace{0.05in}}

\theoremstyle{definition}
\newtheorem*{solution}{Solution}

\usepackage{algpseudocode, algorithm}

%----------------------------------------------------------------------------------------
%	TITLE SECTION
%----------------------------------------------------------------------------------------

\newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height

\title{
\normalfont \normalsize
\textsc{ECS xxx \hfill Dept. of Computer Science, University of California, Davis} % Your university, school and/or department name(s)
\horrule{0.5pt} \\[0.4cm] % Thin top horizontal rule
\huge Homework \#0 \\ % The assignment title
\horrule{2pt} \\[0.5cm] % Thick bottom horizontal rule
}

\author{Your Name and Student ID} % Put your name here

\date{\today}

\begin{document}

\maketitle

Classmate collaborator(s): If you collaborated with fellow students, you \emph{must} list them here.

\section{First Problem}
    \begin{solution}
        Write your solution here.
        You insert math into a sentence using the dollar sign, like this: $f(x) = 2x$.
        Sometimes you need an entire line for an equation, so you use the equation environment, like this:
        \begin{equation*}
            2^{n+1} = \sum_{i=0}^{n} 2^{i}
        \end{equation*}
        If you wish to define an equation that spans multiple lines, use the align environment, like this:
        \begin{align*}
            % This percent denotes a comment.
            % Here, the & tells Latex where to align the text
            % The \\ is required for every line except the last, and it denotes a newline.
            1 + 2 + 2^2 + \ldots + 2^{k+1} &= (1 + 2 + 2^2 + \ldots + 2^k) + 2^{k+1}\\
                &= 2^{k+1} - 1 + 2^{k+1}\\
                &= 2 \cdot 2^{k+1} - 1\\
                &= 2^{k + 2} - 1
        \end{align*}
        If you wish to define a function with cases, use the cases environment, like this:
        \begin{equation*}
            f(n) =
                \begin{cases}
                    n   &   \text{if $n$ is even } \\
                    -n  &   \text{if $n$ is odd}
                \end{cases}
        \end{equation*}
    \end{solution}

\section{Second Problem}
    \begin{solution}
    Sometimes you will want to write proofs. Use the proof environment, like this:
    \begin{proof}
        Suppose that $f:A \to B$ and $g:B \to C$ are injective. Suppose that $x, y \in A$ and $x \neq y$. Then $f(x) \neq f(y)$ because $f$ is injective. Similarly, $g(f(x)) \neq g(f(y))$ because $g$ is injective. Therefore $g \circ f (x) \neq g \circ f (y)$ whenever $x \neq y$, so $g \circ f$ is injective.
    \end{proof}
    \end{solution}

    Sometimes you will want to write algorithms. Use the algorithmic environment, like this:
    \begin{algorithm}
        \caption{YourAlgorithm$(A, B)$}
        \begin{algorithmic}
          \For{$i = 1$ to $n$}
              \If{$A[i] > B[i]$}
                \State $A[i]$ is bigger!
              \Else
                \State $A[i]$ is not bigger!
              \EndIf
          \EndFor
        \State \Return \texttt{True}
        \end{algorithmic}
        \end{algorithm}

    Sometimes you will want to use tables. Use the tabular environment, like this:\\

      \begin{tabular}{|l|cr|}
      $a$ & $b$ & 10\\ \hline
      $e$ & 2 & $d$\\
      \end{tabular}\\

    The argument after the beginning of tabular specifies the columns. l for left justification, c for centered, r for right justification. The bar $|$ creates a vertical line in the table. $\backslash$hline creates a horizontal line in the table.

\section{Third Problem}
    Here is a brief, incomplete list of useful math symbols etc.
    \begin{enumerate}
        \item Exponential $\exp{n}$, $e^n$, $2^n$ etc.
        \item Logarithm $\log$
        \item Big-O $O(f(n))$, Big-Omega $\Omega(f(n))$, Big-Theta $\Theta(f(n))$
        \item Summation $\sum_{i=1}^n i$
        \item Function $f: A \to B$
        \item Union $A \cup B$, Intersection $A \cap B$, Complement $\overline{A}$, Set Difference $A \setminus B$
        \item Set membership $x \in A$
        \item Power Set $\mathcal{P}(A)$
    \end{enumerate}

\end{document}


% ***********************************************************
% ******************* PHYSICS HEADER ************************
% ***********************************************************
% Version 2
\documentclass[12pt]{article}

\usepackage{datetime} % allows easy formatting of dates, e.g. \formatdate{dd}{mm}{yyyy}

\usepackage{amsmath} % AMS Math Package
\usepackage{amsthm} % Theorem Formatting
\usepackage{amssymb}	% Math symbols such as \mathbb
\usepackage{graphicx} % Allows for eps images
\usepackage{multicol} % Allows for multiple columns
\usepackage[dvips,letterpaper,margin=1in,bottom=1in]{geometry}
 % Sets margins and page size
\pagestyle{empty} % Removes page numbers
\makeatletter % Need for anything that contains an @ command
%\renewcommand{\maketitle} % Redefine maketitle to conserve space
%{ \begingroup \vskip 10pt \begin{center} \large {\bf \@title}
%	\vskip 10pt \large \@author \hskip 20pt \@date \end{center}
%  \vskip 10pt \endgroup \setcounter{footnote}{0} }
\makeatother % End of region containing @ commands
\renewcommand{\labelenumi}{(\alph{enumi})} % Use letters for enumerate
% \DeclareMathOperator{\Sample}{Sample}
\let\vaccent=\v % rename builtin command \v{} to \vaccent{}
\renewcommand{\v}[1]{\ensuremath{\mathbf{#1}}} % for vectors
\newcommand{\gv}[1]{\ensuremath{\mbox{\boldmath$ #1 $}}}
% for vectors of Greek letters
\newcommand{\vx}{\ensuremath{\v{x}}}
% for vectors of Greek letters
\newcommand{\vy}{\ensuremath{\v{y}}}
% for vectors of Greek letters
\newcommand{\xdot}{\ensuremath{\dot{x}}}
% for vectors of Greek letters

\newcommand{\ydot}{\ensuremath{\dot{y}}}
% for vectors of Greek letters
\usepackage{commath} % for some nice standardized syntax stuff.
	% \dif, \Dif, \od, \pd, \md, \(abs | envert), \(norm | enVert), \(set | cbr), \sbr, \eval, \int(o | c)(o | c), etc
\newcommand{\bbar}[1]{\bar{\bar{#1}}} % for barring things twice -- use \cbar or \zbar instead of original \bbar

\newcommand{\uv}[1]{\ensuremath{\mathbf{\hat{#1}}}} % for unit vector
%\newcommand{\abs}[1]{\left| #1 \right|} % for absolute value
\newcommand{\avg}[1]{\left< #1 \right>} % for average
\let\underdot=\d % rename builtin command \d{} to \underdot{}
\renewcommand{\d}[2]{\frac{d #1}{d #2}} % for derivatives
\newcommand{\dd}[2]{\frac{d^2 #1}{d #2^2}} % for double derivatives
%\newcommand{\pd}[2]{\frac{\partial #1}{\partial #2}}
% for partial derivatives
\newcommand{\fd}[2]{\frac{\delta #1}{\delta #2}}
% for functional derivatives

\newcommand{\pdd}[2]{\frac{\partial^2 #1}{\partial #2^2}}
% for double partial derivatives
\newcommand{\pdc}[3]{\left( \frac{\partial #1}{\partial #2}
 \right)_{#3}} % for thermodynamic partial derivatives
\newcommand{\ket}[1]{\left| #1 \right>} % for Dirac bras
\newcommand{\bra}[1]{\left< #1 \right|} % for Dirac kets
\newcommand{\braket}[2]{\left< #1 \vphantom{#2} \right|
 \left. #2 \vphantom{#1} \right>} % for Dirac brackets
\newcommand{\matrixel}[3]{\left< #1 \vphantom{#2#3} \right|
 #2 \left| #3 \vphantom{#1#2} \right>} % for Dirac matrix elements
\newcommand{\grad}[1]{\gv{\nabla} #1} % for gradient
\let\divsymb=\div % rename builtin command \div to \divsymb
\renewcommand{\div}[1]{\gv{\nabla} \cdot #1} % for divergence
\newcommand{\curl}[1]{\gv{\nabla} \times #1} % for curl
\let\baraccent=\= % rename builtin command \= to \baraccent
\renewcommand{\=}[1]{\stackrel{#1}{=}} % for putting numbers above =
\newtheorem{prop}{Proposition}
\newtheorem{thm}{Theorem}[section]
\newtheorem{lem}[thm]{Lemma}
\theoremstyle{definition}
\newtheorem{dfn}{Definition}
\theoremstyle{remark}
\newtheorem*{rmk}{Remark}
\newcommand{\bigO}{\mathcal{O}} % big O notation
\let \bigo = \bigO % deprecated version. keeping for now because need to update instances in older files

\makeatletter
% À droite
\renewcommand\subsection{\@startsection {subsection}{1}{\z@}%
                                   {-3.5ex \@plus -1ex \@minus -.2ex}%
                                   {2.3ex \@plus.2ex}%
                                   {\raggedright\normalfont\Large\bfseries}}
\makeatother

\makeatletter
\def\section{\@ifstar\unnumberedsection\numberedsection}
\def\numberedsection{\@ifnextchar[%]
  \numberedsectionwithtwoarguments\numberedsectionwithoneargument}
\def\unnumberedsection{\@ifnextchar[%]
  \unnumberedsectionwithtwoarguments\unnumberedsectionwithoneargument}
\def\numberedsectionwithoneargument#1{\numberedsectionwithtwoarguments[#1]{#1}}
\def\unnumberedsectionwithoneargument#1{\unnumberedsectionwithtwoarguments[#1]{#1}}
\def\numberedsectionwithtwoarguments[#1]#2{%
  \ifhmode\par\fi
  \removelastskip
  \vskip 5ex\goodbreak
  \refstepcounter{section}%
  \hbox to \hsize{\vbox{%
      \noindent
      \leavevmode
      \begingroup
      \Large\bfseries\raggedleft
      \thesection.\
      #2\par
      \endgroup
      \vskip -2ex
      \noindent\hrulefill
      \vskip -2.2ex\nobreak
      \noindent\hrulefill
      }}\nobreak
  \vskip 2ex\nobreak
  \addcontentsline{toc}{section}{%
    \protect\numberline{\thesection}%
    #1}%
  }
\def\unnumberedsectionwithtwoarguments[#1]#2{%
  \ifhmode\par\fi
  \removelastskip
  \vskip 5ex\goodbreak
%  \refstepcounter{section}%
  \hbox to \hsize{\vbox{%
      \noindent
      \leavevmode
      \begingroup
      \Large\bfseries\raggedleft
%      \thesection.\
      #2\par
      \endgroup
      \vskip -2ex
      \noindent\hrulefill
      \vskip -2.2ex\nobreak
      \noindent\hrulefill
      }}\nobreak
  \vskip 2ex\nobreak
  \addcontentsline{toc}{section}{%
%    \protect\numberline{\thesection}%
    #1}%
  }
\makeatother
\pagestyle{empty}

% ***********************************************************
% ********************** END HEADER *************************
% ***********************************************************


%=========================================================================
% sec-opts-loop
%=========================================================================

\section{Changing Loop Ordering}
\label{sec-opts-loop}

% Reason for optimization
\subsection{Reason for Optimization}

The memory access pattern for DGEMM is largely determined by the order in
which the matrices are traversed. Depending on the loop order and the
arrangement of the matrices in memory (i.e., row-major vs. column-major),
memory could be accessed with a unit-stride that maximizes temporal and
spatial locality, or a stride equal to the matrix dimensions that is more
likely to cause cache misses.
\smallskip

The goal of this optimization is to find the loop ordering that uses the
data in a cache line as much as possible before bringing in another cache
line. We explore a variety of loop orderings based on an intuitive
analysis of how to achieve unit-stride memory accesses to identify the
optimal loop ordering.
\smallskip

% Details of optimization
\subsection{Details of Optimization}

\input{fig-opts-loop-access}

The naive loop ordering of {\tt{ijk}} iterates across the output matrix
{\tt{C}}, traversing the columns before traversing the rows. Computing
each element in the output matrix requires traversing the columns of
{\tt{A}} and traversing the rows of {\tt{B}}. This type of access pattern
is generalized in Figure~\ref{fig-opts-loop-access}.
\smallskip

Because the matrices are arranged in a column-major pattern in memory,
it is always preferable to traverse the rows (i.e., vertically) to yield
unit-stride memory accesses. Any time we traverse the columns (i.e.,
horizontally), we only use a single element in a cache line before
accessing another cache line, which makes it more likely to have cache
misses.
\smallskip

Given this, we can see that the naive loop ordering actually generates a
very hostile memory access pattern since the innermost loop always
traverses the columns of {\tt{A}} and the middle loop traverses the
columns of {\tt{C}}.
\smallskip

Fortunately, we can leverage this insight to make an educated guess about
which loop ordering would be preferable. Since the memory access pattern
of the innermost loop is the most critical in exploiting temporal
locality, it makes sense to iterate across {\tt{i}} for the innermost
loop, as this will allow us to traverse the rows of both {\tt{A}} and
{\tt{C}}, while using a single element from {\tt{B}} to calculate the
partial products for an entire column of {\tt{C}}. Note that if the block
size is large, traversing the rows will still require accessing multiple
cache lines, but accessing consecutive cache lines will help avoid
conflict misses more than if we traversed the columns. This means that
either the {\tt{jki}} or the {\tt{kji}} ordering will yield the most
desirable memory access patterns. The former allows us to reuse the same
data for {\tt{B}} and {\tt{C}} while only shifting one column over in
{\tt{A}}, whereas the latter only allows us to reuse the same data in
{\tt{A}}. See Figure~\ref{fig-opts-loop-access} for visual comparisons.
\smallskip

% Results and analysis
\subsection{Results}

\input{fig-opts-loop-results}

The results of all possible loop orderings are shown in
Figure~\ref{fig-opts-loop-results}. We only show the effects of changing
the loop ordering of the computation kernel operating on a given
block. Although we did experiment with changing the loop ordering of the
outer loop that traverses the blocks, the effects on performance were
negligible. This was slightly contrary to expectations as the order in
which the blocks are traversed should impact the reuse of data in
lower-level caches (e.g., L2, L3), whereas the loop ordering of the
computation kernel is more focused on L1 cache utilization.
\smallskip

As expected, the {\tt{jki}} ordering shows the greatest improvement in
performance, followed by the {\tt{kji}} ordering. The other orderings
either exacerbate the sub-optimal memory access patterns or have
negligible improvements over the naive ordering.
\smallskip

One caveat with not iterating over {\tt{k}} in the innermost loop is that
we cannot accumulate the partial products for a given element in the
output matrix in the local register storage. For example, in the
{\tt{jki}} ordering, we must store the partial product for all elements
in a given column in the output matrix to memory, then load each one back
again for the accumulation when {\tt{k}} increments. However, since using
the optimal loop ordering encourages reuse of data in the L1 cache, the
overhead of storing/loading of partial products is not as significant as
if we were using the naive loop ordering.
\medskip

\clearpage


\documentclass[11pt]{article}
\usepackage{amsfonts, amsmath, amssymb, amsthm, fullpage, mdwlist, fancyhdr}

\setlength{\textheight}{9.25in}
\setlength{\textwidth}{6.5in}
\setlength{\topmargin}{0.0in}
\setlength{\headheight}{0.0in}
\setlength{\headsep}{0.0in}
\setlength{\leftmargin}{0.0in}
\setlength{\oddsidemargin}{0.0in}
\setlength{\parindent}{0pc}

\begin{document}

\title{Polynomials II}
\author{Alex Zhu}
\date{KSA Math Olympiad Training 2013}
% date?

\maketitle

\section{Problems}

\begin{enumerate}
  \item (HMMT 2008) Let $S$ be the set of points $(a,b)$ with $0 \leq a,b \leq 1$ such that the equation \[ x^4 + ax^3 - bx^2 + ax + 1 = 0 \] has at least one real root. Determine the area of the graph of $S$.

  \item Let $n$ be a positive odd integer, and let $P$ be a degree $n$ polynomial with $n$ distinct real roots. Prove that $P(P(x))$ has at least $n$ real roots.

  \item Let $x_1, x_2, \ldots, x_n$ be distinct real numbers. Let $b_i = \prod_{j \neq i} (x_i - x_j)$, and let $d_i = \prod_{j \neq i} x_j$. Find $\sum_{i=1}^n \frac{d_i}{b_i}.$

  \item (IMO 1974) Let $P(x)$ be a polynomial of degree $d \geq 1$ with integer coefficients. Let $n(P)$ be the number of integers $k$ for which $P(k)^2 = 1$. Prove that $n(P) - d \leq 2$.

  \item $P$ is a polynomial of degree $n$ with integer coefficients, with $n$ distinct real roots lying between 0 and 1 inclusive. Show that the leading coefficient of $P$ is larger than $2^n$.

  \item Suppose $P$ is a polynomial of degree $n$ with distinct complex roots $\alpha_1, \alpha_2, \ldots, \alpha_n$. The polynomials $Q_1, Q_2, \ldots, Q_n$ are defined so that $P(z) = (z - \alpha_k) Q_k(z)$ for each $z$. Prove that
  \[ Q_1(\alpha_1)^{-1} + Q_2(\alpha_2)^{-1} + \cdots + Q_n(\alpha_n)^{-1} = 0. \]

  \item (IMO 1976) Let $P_1(x) = x^2 - 2$ and $P_j(x) = P_1(P_{j-1}(x))$ for $j \geq 2$. Prove that for any positive integer $n$, the roots of the equation $P_n(x) = x$ are all real and distinct.

  \item (IMO 1975) Determine all polynomials $P$ of two variables satisfying the following three properties:
  \begin{enumerate}
    \item There is a positive integer $n$ such that for any real numbers $t,x,y$, we have $P(tx,ty) = t^n P(x,y)$.
    \item For any real numbers $a,b,c$ we have $P(a+b,c) + P(b+c,a) + P(c+a,b) = 0$.
    \item $P(1,0) = 1$.
  \end{enumerate}

  \item Suppose $p$ is a polynomial with integer coefficients such that $p(n) > n$ for all positive integers $n$. Define the sequence $x_1, x_2, \ldots$ so that $x_1 = 1$ and $x_{n+1} = p(x_n)$ for $n \geq 1$. Suppose that for each positive integer $N$, there exists some $n$ such that $N$ divides $x_n$. Show that $p(x) = x + 1$.

  \item Let $P$ be a polynomial of degree $n$ with real coefficients such that for all $x \in [-1, 1]$, we have $P(x) \in [-1, 1]$. Show that the leading coefficient of $P$ has absolute value at most $2^{n-1}$.

  %\item Let $f$ be a primitive polynomial with integer coefficients of degree $n$ for which there exist distinct integers $x_1, x_2, \ldots, x_n$ such that
  %\[ 0 < |f(x_i)| < \frac{\lfloor \frac{n+1}{2} \rfloor}{2^{\lfloor \frac{n+1}{2} \rfloor}}. \]
  %Prove that $f$ is irreducible in $\mathbb{Z}[x]$.
\end{enumerate}

\end{document}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CS240: Programming in C
% Copyright 2016 Pejman Ghorbanzade <pejman@ghorbanzade.com>
% Creative Commons Attribution-ShareAlike 4.0 International License
% https://github.com/ghorbanzade/UMB-CS240-2016S/blob/master/LICENSE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\def \topDirectory {.}
\def \resDirectory {\topDirectory/src/c/main/ls04}
\def \texDirectory {\topDirectory/src/tex}
\def \styDirectory {\texDirectory/sty}
\def \cfgDirectory {\texDirectory/cfg}
\def \imgDirectory {\texDirectory/img}

\documentclass[compress]{beamer}
%\mode<presentation>
%\usetheme{default}

\usepackage{\styDirectory/directives}
\input{\cfgDirectory/config}
\usepackage{\styDirectory/beamerthemePejman}
\doc{number}{4}
%\setbeamertemplate{footline}[text line]{}

\usepackage{booktabs}

\begin{document}

\prepareCover

\section{Variables}

\begin{slide}
	\begin{block}{Definition}

	A variable is a name for a location in memory used to hold a data value.

	The name of a variable is a sequence of case sensitive letters, digits and the underscore character; the first of which is not a digit.

	\begin{terminal}
	variable_type identifier;
	variable_type identifier = initial_value;
	\end{terminal}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Declaration}

	C is a statically-typed language.
	Type of all variables must be known at compile time.

	A type declaration associates a variable with a type at compile time.

	\begin{terminal}
	int a = 123;
	int b = 99;
	int c = a + b;
	b = 25;
	\end{terminal}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Constants}

	A constant is a special variable that holds a value that may not alter during its lifetime.

	\begin{terminal}
	#define PI 3.14159
	int const PI = 3.14159;
	\end{terminal}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Coding Style Convention}

	\begin{itemize}
	\item[] Avoid long identifiers.
	\item[] Use lowecase for variables.
	\item[] Use uppercase for symbolic constants.
	\item[] Separate words with underscore.
	\end{itemize}

	\end{block}
\end{slide}

\begin{slide}
	\begin{quotation} \scriptsize \normalfont

	C is a Spartan language, and so should your naming be.
	Unlike Modula-2 and Pascal programmers, C programmers do not use cute names like \alert{\texttt{ThisVariableIsATemporaryCounter}}.
	A C programmer would call that variable \alert{\texttt{tmp}}, which is much easier to write, and not the least more difficult to understand.

	[...]

	Local variable names should be short, and to the point.
	If you have some random integer loop counter, it should probably be called \alert{\texttt{i}}.
	Calling it \alert{\texttt{loop\_counter}} is non-productive, if there is no chance of it being mis-understood.
	Similarly, \alert{\texttt{tmp}} can be just about any type of variable that is used to hold a temporary value.

	If you are afraid to mix up your local variable names, you have another problem, which is called the function-growth-hormone-imbalance syndrome.

	\begin{flushright}-- Linux Kernel Coding Style\end{flushright}

	\end{quotation}
\end{slide}

\section{Data Types}

\begin{slide}
	\begin{block}{Definition}

	The type of a variable determines the number of bytes to be assigned to its value and how the bit pattern of its value should be interpreted.

	\begin{terminal}
	int a = 7;
	\end{terminal}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Basic Data Types}

	\begin{columns}
	\column{0.3\textwidth}
	\begin{itemize}
	\item[] int
	\item[] char
	\end{itemize}

	\column{0.4\textwidth}
	\begin{itemize}
	\item[] double
	\item[] float
	\end{itemize}

	\column{0.3\textwidth}
	\begin{itemize}
	\item[] void
	\end{itemize}
	\end{columns}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Signed vs. Unsigned}

	By default, the left-most bit of a variable is reserved to indicate sign of its value.
	If the value of a variable is ensured to be non-negative, it is possible to instruct the compiler not to reserve a \emph{sign} bit.

	\begin{terminal}
	int a;
	unsigned int b;
	\end{terminal}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Integer Data Types}

	You can instruct the compiler to reserve less or more bytes for an integer variable.

	\begin{itemize}
	\item[] short
	\item[] long
	\end{itemize}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Integer Types}

	\begin{table}
	\begin{tabular}{lcc}
	\toprule
	Type & Storage Size & Value Range \\
	\midrule
	char & 1 byte & -128 to 127 \\
	int & 4 bytes & $-2^{32-1}$ to $2^{32-1}$ \\
	short & 2 bytes & -32768 to 32767 \\
	long & 8 bytes & $-2^{64-1}$ to $2^{64-1}$ \\
	\bottomrule
	\end{tabular}
	\end{table}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Floating-Point Types}

	\begin{table}
	\begin{tabular}{lcc}
	\toprule
	Type & Storage Size & Value Range \\
	\midrule
	float & 4 bytes & 1.2E-38to 3.4E+38 \\
	double & 8 bytes & 2.3E-308 to 1.7E+308 \\
	long double & 16 bytes & 3.36E-4932 to 1.19E+4932 \\
	\bottomrule
	\end{tabular}
	\end{table}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Void Type}

	The \alert{void} data type is used to indicate that no value is available.
	It is used in three situations:

	\begin{itemize}
	\item[] To specify type of return value of a function that does not return anything.
	\item[] To specify type of argument of a function that does not accept any argument.
	\item[] To access address of a data object instead of its value.
	\end{itemize}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Note}

	Declared data type should be consistent with the value assigned.

	\inputminted[
		fontsize=\scriptsize,
		firstline=14,
		lastline=19,
		linenos
	]{c}{\resDirectory/hello-cmd1.c}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Remember}

	\begin{itemize}
	\item[] C does not provide a boolean data type.
	\item[] C does not provide a String data type.
	\end{itemize}

	\end{block}
\end{slide}

\begin{slide}
	\begin{figure}
	\includegraphics[width=0.8\textwidth]{\imgDirectory/boolean.jpg}
	\end{figure}
\end{slide}

\section{Command Line Arguments}

\begin{slide}
	\begin{block}{Definitions}

	Command line arguments are a list of string literals separated by whitespace with which your program is invoked.

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Motivation}

	Command line arguments provide efficient interthread communication through piping and redirection.

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Implementation}

	\inputminted[
		fontsize=\scriptsize,
		firstline=10,
		linenos
	]{c}{\resDirectory/hello-cmd1.c}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Demonstration}

	\begin{terminal}
	pejman@cs240$ gcc hello-cmd.c -o hello-cmd
	pejman@cs240$ ./hello-cmd CS240
	Hello CS240!
	pejman@cs240$ ./hello-cmd Pejman
	Hello Pejman!
	pejman@cs240$ ./hello-cmd Mr President
	Hello Mr!
	\end{terminal}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Problem Statement}

	A programmer has no prior knowledge of how the program will be executed.

	\begin{terminal}
	pejman@cs240$ gcc hello-cmd.c -o hello-cmd
	pejman@cs240$ ./hello-cmd
	Hello (null)!
	\end{terminal}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Proposed Solution}

	\inputminted[
		fontsize=\scriptsize,
		firstline=10,
		linenos
	]{c}{\resDirectory/hello-cmd2.c}

	\end{block}
\end{slide}

\begin{slide}
	\begin{block}{Notes}

	\begin{itemize}
	\item[] All command line arguments are given before program execution.
	\item[] Each command line argument is an array of character.
	\end{itemize}

	\end{block}
\end{slide}

\begin{slide}
	\begin{figure}
	\includegraphics[width=0.6\textwidth]{\imgDirectory/sudo.png}
	\end{figure}
\end{slide}

\end{document}


\documentclass{article}
\pagestyle{empty}
\usepackage{amsmath,amssymb,amsfonts}
\usepackage{graphicx}
\usepackage{multicol}
\setlength{\oddsidemargin}{0in} \setlength{\evensidemargin}{0in}
\setlength{\topmargin}{0in} \setlength{\textheight}{8.5in}
\setlength{\textwidth}{6.5in}

\makeatletter
\renewcommand*\env@matrix[1][*\c@MaxMatrixCols c]{%
	\hskip -\arraycolsep
	\let\@ifnextchar\new@ifnextchar
	\array{#1}}
\makeatother

\begin{document}
\begin{flushleft}
	\bfseries{MATH 260, Linear Algebra, Spring `14}\\
	\bfseries{Activity 6:  Determinants and Cramer's Rule}\\
	\bfseries{Honor Code:} \hspace{3.5in}\bfseries{Names:}\\
\end{flushleft}
\begin{flushleft}
\vspace{.75in}
Directions:  Everyone should work on the assignment and should fill out their paper.  You are expected to make corrections based on what is presented on the board.  \\
\large The worksheet is due by the end of the day (5pm). \normalsize \\
If you need more explanations after class, you can read Chapter 3.4 of your textbook.\\
\vspace{0.1in}
\Large
In-Class Learning Goals:\\
\normalsize
\begin{enumerate}
\item Be able to find the determinant of a matrix (both $2\times 2$ AND nXn).
\item Be able to find the `minor' and `cofactor' of elements in a matrix.
\item Be able to find solutions to a system using \textit{Cramer's Rule}.
\item (Stretch) Discover several properties of determinants including if a matrix has an inverse.
\end{enumerate}

\vspace{0.1in}
\begin{center}
\section*{Warmup: Determinant of a $2 \times 2$}
$|\textbf{A}| = \begin{vmatrix}[rr] a_{11} & a_{12} \\ a_{21} & a_{22} \end{vmatrix} = a_{11} a_{22} - a_{12} a_{21}$\\
\vspace{0.2in}
\textit{Note:} You will need to have this formula memorized!\\
\end{center}
Find the determinant of the following matrix:\\
\begin{center}
$\begin{bmatrix}[rr]
-3 & 1   \\
4 & 2
\end{bmatrix}
$
\hspace{1in}
$\begin{bmatrix}[rrr]
3 & 0 & -1\\
0 & 0 &  3 \\
0 & 1 & 0
\end{bmatrix}
$
\end{center}
\vspace{2in}

\newpage
\begin{center}
\section{Some Properties and Practice}
\end{center}
For \textbf{Activity 5} you found several inverses and transposes of matrices. Lets use them...\\
\begin{center}
$\textbf{H}=\begin{bmatrix}[rr]
1 & 1\\
4  & 1
\end{bmatrix}$
\hspace{0.5in}
$\textbf{H}^{-1}=\left[
\begin{array}{cc}
- \frac{1}{3} & \frac{1}{3} \vspace{0.1in}\\

\frac{4}{3} & - \frac{1}{3}
\end{array} \right]$
\hspace{0.5in}
$
\textbf{H}^{T}=\begin{bmatrix}[rr]
1 & 4\\
1  & 1
\end{bmatrix}$
\hspace{0.5in}
$\textbf{G}=
\begin{bmatrix}[rrr]
3 & 0 & 3\\
-1 & 2 & 1\\
1 & 1 & 2
\end{bmatrix}$\\
\end{center}

\vspace{0.1in}
a) Find $|\textbf{H}|$.\\
\vspace{0.8in}
b) Find $|\textbf{H}^{-1}|$.\\
\vspace{0.8in}
c) Find $|\textbf{H}^{T}|$.\\
\vspace{0.8in}
d) Find $|\textbf{G}|$.\\
\vspace{1in}
e) Are any of the numbers above the same? Closely related? Try to write each as a generalized property (check these with me).
\newpage
\begin{center}
\section{Finding Minors (and some $2 \times 2$ practice)}
\small This method is only a little harder than visiting an elementary school... \normalsize
\end{center}
\textbf{Definition:} For the $n \times n$ matrix \textbf{A}, the \textit{minor $M_{ij}$} of $a_{ij}$ is an $(n-1) \times (n-1)$ matrix obtained by deleting the $i$th row and the $j$th column of \textbf{A}. \\
\begin{center}
$\textbf{A}=
\begin{bmatrix}
\bullet &\bullet &\bullet & \bullet \\
\bullet &\bullet &\bullet & \bullet \\
\bullet &\bullet &\bullet & \bullet \\
\bullet &\bullet &\bullet & \bullet \\
\end{bmatrix}
=
\begin{bmatrix}[rrrr]
1&2&3&1\\
5&0&1&-2\\
4&0&1&0\\
2&0&3&1
\end{bmatrix}
$
\hspace{0.4in}
$\textbf{M}_{12}=
\begin{bmatrix}
\circ & \circ & \circ & \circ \\
\bullet & \circ & \bullet & \bullet \\
\bullet & \circ & \bullet & \bullet \\
\bullet & \circ & \bullet & \bullet \\
\end{bmatrix}
\rightarrow
\begin{bmatrix}
\bullet & \bullet & \bullet \\
\bullet & \bullet & \bullet \\
\bullet & \bullet & \bullet \\
\end{bmatrix}
=
\begin{bmatrix}[rrr]
5 & 1&-2\\
4 & 1& 0\\
2&3&1
\end{bmatrix}$
\end{center}
a) Find the minor $\textbf{M}_{32}$ of \textbf{A}. To show your work, re-write \textbf{A} first...\\
\vspace{1.5in}
b) Lets find some minors of minors... \\
(i) Find $\textbf{M}_{21}$ of $\textbf{M}_{12}$\\
\vspace{0.75in}
(ii) Find $\textbf{M}_{22}$ of $\textbf{M}_{12}$\\
\vspace{0.75in}
(iii) Find $\textbf{M}_{23}$ of $\textbf{M}_{12}$\\
\vspace{0.75in}
c) Find the determinant of...\\
(i) $\textbf{M}_{21}$\\
\vspace{0.75in}
(ii) $\textbf{M}_{22}$\\
\vspace{0.75in}
(iii) $\textbf{M}_{23}$

\newpage
\begin{center}
\section{Co-Factors}
\end{center}
\textbf{Definition:} The \textit{co-factor} of an element $a_{ij}$ is the scalar: $C_{ij}=(-1)^{i+j}|\textbf{M}_{ij}|$\\
\vspace{0.1in}
Notice that the co-factor is just the determinant of a minor, times $\pm 1$. We'll use this in the next section...
a) Find $C_{21}$ of $\textbf{M}_{12}$\\
\vspace{0.75in}
b) Find $C_{22}$ of $\textbf{M}_{12}$\\
\vspace{0.75in}
c) Find $C_{23}$ of $\textbf{M}_{12}$\\
\vspace{0.75in}
d) Can you find $C_{12}$ of \textbf{A} (based on what you know now)? Why or why not?\\
\vspace{1in}

\begin{center}
\section{Determinants of N x N matrices}
\end{center}
Lets start by finding the determinant of the 3x3 matrix $\textbf{M}_{12}$. \\
To make our notation simpler, lets call $\textbf{M}_{12}$ matrix \textbf{D}.\\
a) Find the following sum: \hspace{0.2in} $d_{21}*C_{21} + d_{22}*C_{22} + d_{23}*C_{23}$ \\
\textit{Hint: You should get a single, scalar number.}\\
\vspace{1in}
b) Try writing the sum for (a) in summation notation (i.e. using: $\Sigma$).\\

\newpage
\LARGE \begin{center} Determinants of N x N matrices (cont.) \end{center} \normalsize
Finding the determinant of an NxN matrix is a recursive process. The definition is:\\
\vspace{0.1in}
\textbf{Definition:} Choose a row $i$ or column $j$, then $|A|=\sum\limits^{n}_{(j \text{ or } i)} a_{ij} C_{ij} = \sum\limits^{n}_{j \text{ or } i} a_{ij} (-1)^{i+j} |\textbf{M}_{ij}| $\\
\vspace{0.1in}
Notice that $\textbf{M}_{ij}$ may not be a $2 \times 2$!! You might have to use this process several times. \\
\vspace{0.1in}
c) Using this definition find the determinant of our original \textbf{A} matrix. \\
\textit{Hint: You should only need to do a few new multiplications and additions, you calculated most of it already.}\\
\vspace{1in}

\end{flushleft}
\end{document}

Spring 2014 - Schmitt/Activity Latex/Activity_6_260_Determinants.tex


\documentclass[12pt]{article}

\include{preamble}

\newtoggle{spacingmode}
\toggletrue{spacingmode}  %STUDENTS: DELETE or COMMENT this line

\newtoggle{professormode}
\toggletrue{professormode} %STUDENTS: DELETE or COMMENT this line

\newcommand{\spc}[1]{\iftoggle{spacingmode}{\\ \vspace{#1cm}}}

\title{MATH 241 Fall \the\year~Homework \#6}

\author{Professor Adam Kapelner} % STUDENTS: DELETE my name and put your name and section here e.g. \author{John Doe, Section A}. MAKE SURE YOU PUT YOUR SECTION HERE!!!!!!!!

\iftoggle{professormode}{
\date{NOT DUE but covered on the final exam \\ \vspace{0.5cm} \small (this document last updated \today ~at \currenttime)}
}

\renewcommand{\abstractname}{Instructions and Philosophy}

\begin{document}
\maketitle

\iftoggle{professormode}{
\begin{abstract}
The path to success in this class is to do many problems. Unlike other courses, exclusively doing reading(s) will not help. Coming to lecture is akin to watching workout videos; thinking about and solving problems on your own is the actual ``working out''.  Feel free to \qu{work out} with others; \textbf{I want you to work on this in groups.}

Reading is still \textit{required}. For this homework set, read about the central limit theorem, confidence intervals and hypothesis tests for one proportion.

The problems below are color coded: \ingreen{green} problems are considered \textit{easy} and marked \qu{[easy]}; \inorange{yellow} problems are considered \textit{intermediate} and marked \qu{[harder]}, \inred{red} problems are considered \textit{difficult} and marked \qu{[difficult]} and \inpurple{purple} problems are extra credit. The \textit{easy} problems are intended to be ``giveaways'' if you went to class. Do as much as you can of the others; I expect you to at least attempt the \textit{difficult} problems.

This homework is worth 100 points but the point distribution will not be determined until after the due date. See syllabus for the policy on late homework.

Up to [see syllabus] points are given as a bonus if the homework is typed using \LaTeX. Links to instaling \LaTeX~and program for compiling \LaTeX~is found on the syllabus. You are encouraged to use \url{overleaf.com}. If you are handing in homework this way, read the comments in the code; there are two lines to comment out and you should replace my name with yours and write your section. If you are asked to make drawings, you can take a picture of your handwritten drawing and insert them as figures or leave space using the \qu{$\backslash$vspace} command and draw them in after printing or attach them stapled.

The document is available with spaces for you to write your answers. If not using \LaTeX, print this document and write in your answers. I do not accept homeworks not on this printout. Keep this first page printed for your records. Write your name below.

\end{abstract}

\thispagestyle{empty}
\vspace{1cm}
NAME: \line(1,0){240} %~~SECTION (A or B): \line(1,0){35}
\pagebreak
}~\\

\problem{Now that we've now proven the CLT, we are going to use it a little bit. Assume $X_1, \ldots, X_n \iid$ something with mean $\mu$ and standard error $\sigma$.}

\begin{enumerate}

\easysubproblem{Assume $n$ is large enough for the CLT to kick in, show that:

\beqn
\Xbar \sim \normnot{\mu}{\squared{\frac{\sigma}{\sqrt{n}}}}
\eeqn }\spc{3}

\easysubproblem{Assume $n$ is large enough for the CLT to kick in, show that:

\beqn
T_n \sim \normnot{n\mu}{\squared{\sqrt{n}\sigma}}
\eeqn }\spc{3}

\easysubproblem{Let $X_1, \ldots, X_n \iid \bernoulli{p}$ and let $\Phat := \Xbar$. Assume $n$ is large enough for the CLT to kick in, show that:

\beqn
\Phat \sim \normnot{p}{\squared{\sqrt{\frac{p(1-p))}{n}}}}
\eeqn }\spc{3}

\easysubproblem{Draw the PDF of $\Phat_n$ below. On the $\phat$ axis, mark a tick for the mean, and ticks for three standard errors above the mean and ticks for three standard errors below the mean. I'm giving almost a full page for this because other problems depend on it. Use 1/3 of the space for your drawing of the PDF.  }\spc{15}

\hardsubproblem{If $\Xoneton \iid \bernoulli{p}$ and assuming $n$ is big enough for the CLT to \qu{kick in} as well as what you know about normal distributions shifted and scaled, provide the PDF of $\Phat_n$. This will force you to understand (1) the generalized density for $\normnot{\mu}{\sigsq}$ which is in the notes but has never been previously asked on a homework assignment, (2) substitutions for the mean and variance and (3) what the free variable is. }\spc{2}

\intermediatesubproblem{Let's say $p=0.2$ and $n = 100$. What is $\prob{\Phat_n \geq 0.24}$? You will need to use shifts and scales to get it to look like $\prob{Z > z}$ where $Z$ is the standard normal and $z$ is 0.24 standardized.  }\spc{6}

%\hardsubproblem{Let's say $p=0.2$ and $n = 100$. What is the probability of realizing a $\phat$ above 0.3? Without a computer, you cannot answer this exactly. Just using the empirical rule, find the lower and upper bound of this probability. Do not answer exactly. I will not ask you to answer exactly on the test but I will ask you to find a lower and upper bound using the empirical rule.  }\spc{5}

\end{enumerate}

\iftoggle{professormode}{
\paragraph{Basics of Statistical Inference}~\\ \\
}

\problem{We have now used the CLT to understand the distribution of sample proportions. Here, we will assume that $p$, the true proportion of \qu{success,} is unknown and we will try to infer it. This is a problem of paramount importance. Imagine you're polling for a political candidate. You really do want to know $p$ --- the proportion of people who will vote for your candidate. Imagine you're investigating a drug with side effects. You really do want to know $p$ --- the proportion of people who suffer from that side effect.}

\begin{enumerate}

\easysubproblem{If you have realizations of $\Xoneton \iid \bernoulli{p}$, call them $\xoneton$, what is your best guess of $p$? This is called a \qu{point estimate.} Make sure to use the special notation for this estimate we used in class and define it mathematically.  }\spc{2}

\hardsubproblem{Write \textit{in English} why $\phat \neq p$. I marked this as hard because you need to really use your knowledge about random variables, realizations and parameters and get all these concepts straight.  }\spc{4}

\intermediatesubproblem{Reference the picture in 3(d). Where are the \qu{middle} 95\% of $\phat$'s realized? When I say \qu{middle} I mean the 95\% that are \textit{closest} to $p$, the true expected value. Write the interval that corresponds to this set of numbers. Use the bracket set notation we learned in lecture 1.  }\spc{2}

%\intermediatesubproblem{The interval you created in (c) left out 5\% of the density of $\Phat_n$. Write the set that corresponds to this left out set. Use the union notation from lecture 1.  }\spc{2}

\easysubproblem{What is the width of the interval you created in (c)?  }\spc{0.5}

\easysubproblem{What is the half width of the interval you created in (c)?  }\spc{1}

\easysubproblem{In your picture in 3(d), draw a dotted line from the center of the PDF, $p$ down the length of the page. Create a realization of $\Phat$, call it $\phat$ within the interval in (c) and mark it as a solid dot. Then carefully measure using a ruler, one half width (f) from the fot to the left and one half width from (f) to the right and draw these two lines and mark the ends with a square bracket. No need to write anything below this prompt.}

\easysubproblem{Did this interval \textit{cover} $p$? That is, does it include $p$? You can see if it includes the dotted line drawn down from $p$.  }\spc{1}

\easysubproblem{Would all $\phat$'s realized within the interval in (c) cover $p$?  Yes/no.}\spc{1}

\hardsubproblem{Prove that the probability that the interval covers $p$ is 95\%. We did this in class.  }\spc{4}

\easysubproblem{Illustrate an example of a $\phat$ with the same half-width to the left and right interval that does \textit{not} cover $p$ in your picture of 3(d). No need to write anything here.}

\intermediatesubproblem{In what set do the $\phat$'s such as in (k) come from that fail to cover $p$?  }\spc{1}

\end{enumerate}

\problem{Now we'll just practice building CI's and ask some questions about the procedure.}

\begin{enumerate}

\intermediatesubproblem{Why is it important to have a simple random sample (a completely random sample) when sampling from a population? Write a couple sentences \textit{in English}.  }\spc{4}

\easysubproblem{Write the mathematical definition of a two-sided $1-\alpha$ confidence interval below for a one-sample binomial proportion.  }\spc{1}

\easysubproblem{In the notation above, the \qu{CI} has two subscripts. What do these two subscripts mean?  }\spc{2}

\hardsubproblem{The above CI in (b) does not give \textit{exact} coverage, but only \textit{approximate} coverage for two separate reasons. What are the two reasons? Assume the realizations are indeed sampled from $\iid$ Bernoulli r.v.'s and it was a simple random sample.  }\spc{4}

\easysubproblem{As in the example done in class, imagine we sampled 594 M\&M's and found that 116 were blue. Compute a 95\% CI for $p$, the true proportion of blue M\&M's. Assume all of the CI assumptions are correct.  }\spc{2}

\easysubproblem{Compute a 99\% CI for $p$, the true proportion of blue M\&M's using the same data as in (e). Assume all of the CI assumptions are correct. I gave you this $z_{\overtwo{\alpha}}$ value in class. }\spc{4}

\hardsubproblem{The 99\% CI is larger than the 95\% CI. This is because $z_{\overtwo{\alpha}}$ increased because we requested wider confidence which increases the margin of error (the margin of error is the $z_{\overtwo{\alpha}}\sqrt{\frac{\phat(1-\phat)}{n}}$ term). Let's say we wanted a 99\% CI with the same width as the 95\% CI. How much more M\&M's would we have to look at to do so?  }\spc{6}

\intermediatesubproblem{Let's say we wanted to be sure we captured $p$ in the CI. What's the problem with just making our $1-\alpha$ really large like 99.99999\% (or $\alpha$ really small like 0.000001\%)? Answer \textit{in English}.  }\spc{4}

\easysubproblem{For the interval you created in (e) provide three valid classical interpretations for it \textit{in English}.  }\spc{5}

%\easysubproblem{For the interval you created in (e) write the non-classical i.e subjective interpretation \textit{in English} --- this is the interpretation you really want to be able to say...  }\spc{3}

\easysubproblem{We were interested in political orientation at Queens College. We polled 100 students and 38 of them were registered democrats. Create a 95\% confidence interval for the true proportion of registered democrats at Queens College.  }\spc{4}

\easysubproblem{To get these 100 students, imagine we asked students who were waiting at the Q64 bus stop. Would there then be any problems with the CI we created in (k)? Answer \textit{in English}.  }\spc{3}

\intermediatesubproblem{What would be the best way (or at least a better way) to sample 100 students in order to create the most accurate CI in (k)? Answer \textit{in English}.  }\spc{7}

\end{enumerate}

\problem{CI's are for inference but hypothesis testing is for assessing whether a certain theory is grounded. This will be the last topic covered on the Math 241 final. We will illustrate by using the human sex ratio example from class.}

\begin{enumerate}

\easysubproblem{We a priori assume an equal sex ratio. We'll define $p$ as the probability of being male arbitrarily. What is the null hypothesis expressed using the mathematical notation we used in class? }\spc{1}

\easysubproblem{What would be the alternative hypothesis expressed using the mathematical notation we used in class? }\spc{1}

\intermediatesubproblem{If $n=200$, what is the null distribution? No symbols are acceptable as an answer, you must calculate exactly what the distribution is. Draw this null distribution how we did in class. }\spc{6}

\intermediatesubproblem{Let's say failing to find a deviation from the hypothesized equal sex ratio meant you get fired from your boss (who believes in the unequal sex ratio theory). What kind of $\alpha$ would you pick for this test? Justify using a sentence \textit{in English}. }\spc{3}

\easysubproblem{Regardless of the $\alpha$ chosen, choose $\alpha = 1\%$. What is the retainment region under $\alpha = 1\%$? Denote it on the drawing in (c). }\spc{2}

\easysubproblem{What is the rejection region under $\alpha = 1\%$? Use the $\cup$ symbol to join the two sets. Denote it on the drawing in (c). }\spc{2}

\easysubproblem{What is a Type I error in general? Answer \textit{in English}. }\spc{3}

\easysubproblem{What does a Type I error mean in this human sex ratio experiment? Answer \textit{in English}. }\spc{3}

\easysubproblem{What is the probability of the Type I error in this example? }\spc{1}

\easysubproblem{What is a Type II error in general? Answer \textit{in English}. }\spc{3}

\easysubproblem{What does a Type II error mean in this human sex ratio experiment? Answer \textit{in English}. }\spc{3}

\easysubproblem{You count there are 113 males. Calculate $\phat$ and denote it on the drawing in (c).  }\spc{3}

\easysubproblem{What is the result of the hypothesis test? Do you retain $H_0$ or reject $H_0$? Write a sentence in English interpreting what this means.  }\spc{4}

\hardsubproblem{Now let $n=4,247,000$ (the number of American newborns in the year 2008) and use the same $\alpha =1\%$. You get 2,173,000 males. Write the hypotheses, find the retainment region and find the result and interpret it. }\spc{9}

%\extracreditsubproblem{Why is the human sex ratio not even? Write your thoughts below with sources. }\spc{5}

\end{enumerate}

\problem{This last example involved two-sided hypothesis tests of one proportion. Here, we will examine the case of firing the Uber driver where we only care about only testing one side.

The Uber driver takes 1,000 rides and then the company makes a decision about whether or not he's a good driver based on an arbitrary rule of having more than $p=$ 5\% true proportion / propensity of bad rides. [optional]}

\begin{enumerate}

\easysubproblem{Detecting him being a bad driver is sounding the alarm. Thus the status quo is that he's a good driver. Thus, $H_0: p \leq 0.05$. What is $H_a$ here?  [optional] }\spc{1}

\intermediatesubproblem{At $\alpha$ = 2.5\%, what is the retainment region?  [optional]}\spc{2}

\easysubproblem{At $\alpha$ = 2.5\%, what is the rejection region?  [optional]}\spc{2}

\easysubproblem{The driver under investigation had 62 badly reviewed rides out of 1,000 rides. Calculate $\phat$ and say if it's above the $p$ cutoff Uber is using.  [optional]}\spc{1}

\intermediatesubproblem{If the driver under investigation had 62 badly reviewed rides out of 1,000 rides, would Uber fire him? Run the hypothesis test now and see. Hint: the answer to the (d) will mislead you. [optional] }\spc{8}

%\hardsubproblem{You may be wondering why on Earth we defined $H_a$ the way we did in (a). Wouldn't it seem more natural to switch the null and alternative hypothesis? Switch them here and run the test again. }\spc{6}
%
%\hardsubproblem{Your answer changed! Why is it a bad idea to run the test like in (f) / why is it a better idea to run the test like in (e)? }\spc{4.5}

\extracreditsubproblem{Find the $p$-val for the test in (e). }\spc{0}

\extracreditsubproblem{If the driver's true proportion / propensity of bad rides is $6\%$, what is the probability of a type II error when running the test in (e)? Then calculate power (1 - the probability of a type II error).}\spc{0}

\end{enumerate}

\problem{This will teach you about $H_0$ and $H_a$ using a silly example.} %This problem is optional and will not be graded.}

\iftoggle{professormode}{
\begin{figure}[htp]
\centering
\includegraphics[width=2in]{ufo.jpg}
\end{figure}
}

\begin{enumerate}

\easysubproblem{Consider $H_0$: Aliens do not exist vs $H_a$: Aliens do exist. Why is this a \qu{standard} hypothesis test? }\spc{1}

\easysubproblem{Describe a person using English who has a high $\alpha$ for $H_0$: Aliens do not exist vs $H_a$: Aliens do exist. }\spc{1}

\easysubproblem{Describe a person using English who has a low $\alpha$ for $H_0$: Aliens do not exist vs $H_a$: Aliens do exist. }\spc{1}

\easysubproblem{Describe a person using English who has a high $\alpha$ for $H_0$: Aliens do exist vs $H_a$: Aliens do not exist. }\spc{1}

\easysubproblem{Describe a person using English who has a low $\alpha$ for $H_0$: Aliens do exist vs $H_a$: Aliens do not exist.  }\spc{2}

\end{enumerate}

\end{document}