\section{Divide and Conquer}
\toclesssubsection{Introduction}
\label{chap:divide_and_conquer}

%-------------------------------------------------------------------------------

\begin{frame}{Divide and Conquer}{Introduction}
  \textbf{Concept:}
  \begin{itemize}
    \item<2->
      {\color{MainA}Divide} the problem into smaller subproblems
    \item<3->
      {\color{MainA}Conquer} the subproblems through recursive solving.\\
      If subproblems are small enough solve them directly
    \item<4->
      {\color{MainA}Connect} all solutions of the subproblems to the solution of the
      full problem
    \item<5->
      {\color{MainA}Recursive} application of the algorithm to ever smaller
      subproblems
    \item<6->
      {\color{MainA}Direct} solving of sufficiently small subproblems
  \end{itemize}
\end{frame}

%-------------------------------------------------------------------------------

\codeslide{python}{
  \begin{frame}{Divide and Conquer}{Introduction - Python}
    \begin{itemize}
      \item<2->Function {\color{MainA}solve} for solving a {\color{MainA}problem} of size {\color{MainA}$n$}
    \end{itemize}
  \onslide<3->
  \vspace{-0.5em}
  \lstinputlisting[
    language=Python,
    basicstyle=\small,
    tabsize=4,
    style={python-idle-code},
    escapechar={@},
    emph={solve},
    emphstyle=\color{blue}
  ]{Code/DivideAndConquer/DivideAndConquer_Concept.py}
\end{frame}
}

%TODO: Implement for Java / C++

%-------------------------------------------------------------------------------

\begin{frame}{Divide and Conquer}{Features}
  \textbf{Divide and Conquer:}
  \begin{itemize}
    \item<2-| handout: 1>
      Can help with conceptual hard problems
    \item<3-| handout: 1>
      {\color{MainA}Solution} of the trivial problems has to be known
    \item<4-| handout: 1>
      {\color{MainA}Dividing} into subproblems has to be possible
    \item<5-| handout: 1>
      {\color{MainA}Combination} of solutions has to be possible
  \end{itemize}
\end{frame}

%-------------------------------------------------------------------------------

\begin{frame}{Divide and Conquer}{Features}
  \textbf{Features:}
  \begin{itemize}
    \item<1->
      Realization of {\color{MainA}efficient solutions}
      \begin{itemize}
        \item<2->
          If trivial solution is {\color{MainA}$\in O(1)$}
        \item<3->
          And separation / combination of subproblems is
          {\color{MainA}$\in O(n)$}
        \item<4->
          And the number of subproblems is limited
        \item<5->
          The runtime is {\color{MainA}$\in O(n \cdot \log n)$}
      \end{itemize}
    \item<6->
      Suitable for parallel processing
      \begin{itemize}
        \item<7->
          Parallel processing of subproblems possible since subproblems are {\color{MainA}independent} of each other
      \end{itemize}
  \end{itemize}
\end{frame}

%-------------------------------------------------------------------------------

\begin{frame}{Divide and Conquer}{Implementation}
  \textbf{Definition of the trivial case:}
  \begin{itemize}
    \item<2->
      Smaller subproblems are elegant and simple
    \item<3->
      On the other hand the efficiency will be improved if relatively big subproblems
      can be solved directly
    \item<4->
      Recursion depth should not get too big (stack / memory overhead)
  \end{itemize}
\end{frame}

%-------------------------------------------------------------------------------

\begin{frame}{Divide and Conquer}{Implementation}
  \textbf{Division in subproblems:}
  \begin{itemize}
    \item<2->
      Choosing the number of subproblems and the concrete allocation can be
      demanding
  \end{itemize}
  \onslide<3->
  \vspace{1em}
  \textbf{Combination of solutions:}
  \begin{itemize}
    \item<4->
      Typically conceptionally demanding
  \end{itemize}
\end{frame}

%-------------------------------------------------------------------------------

\begin{frame}{Divide and Conquer}{Example - Maximum Subtotal}
  \textbf{Example - Maximum Subtotal}
   \onslide<2->
   \textbf{Input:}
    \onslide<3->
  \begin{itemize}
    \item<4->
      Sequence {\color{MainA}$X$} of {\color{MainA}$n$} integers
  \end{itemize}
   \onslide<5->
  \textbf{Output:}
  \begin{itemize}
    \item<6->
      Maximum sum of related subsequence and its index boundary
  \end{itemize}
   \onslide<7->
    \vspace{1em}
    \begin{table}[!t]
      \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c}
        Index & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9\\
        \midrule
        Value & 31 & -41 & 59 & 26 & -53 & 58 & 97 & -93 & -23 & 84
      \end{tabular}
      \end{table}
    \onslide<8->
  \textbf{Output:} sum: 187, start: 2, end: 6
\end{frame}

%-------------------------------------------------------------------------------

%% \begin{frame}{Divide and Conquer}{Example - Maximum Subtotal}
%%   \begin{example}[Maximum Subtotal]
%%     \vspace{-1em}
%%     \begin{table}[!t]
%%       \caption{Input values}
%%       \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c}
%%         Index & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9\\
%%         \midrule
%%         Value & 31 & -41 & 59 & 26 & -53 & 58 & 97 & -93 & -23 & 84
%%       \end{tabular}
%%       \label{tab:divide_and_conquer:max_subtotal_example_values}
%%     \end{table}
%%     \vspace{6em}
%%     %TODO: Hand-Drawings here (Free space) or no free space?

%%     \textbf{Output:} Sum: 187, Start: 2, End: 6
%%   \end{example}
%% \end{frame}

%-------------------------------------------------------------------------------

\begin{frame}{Divide and Conquer}{Example - Maximum Subtotal}
  \textbf{Application:}
  \begin{itemize}
    \item
      Maximum profit of buying and selling shares
  \end{itemize}
  \begin{figure}
    \begin{center}
      \includegraphics[width=0.9\textwidth]%
        {Images/DivideAndConquer/shares-graph.pdf}
    \end{center}
    \caption{stock value over time}
    \label{fig:divide_and_conquer:shares_value}
  \end{figure}
\end{frame}

%-------------------------------------------------------------------------------

\codeslide{python}{
  \begin{frame}{Divide and Conquer}{Example - Maximum Subtotal - Python}
    \textbf{Naive solution (brute force)}
    \onslide<2->
      \vspace{-0.5em}
      \lstinputlisting[
        language=Python,
        basicstyle=\small,
        tabsize=4,
        style={python-idle-code},
        escapechar={@},
        emph={maxSubArray},
        emphstyle=\color{blue}
      ]{Code/DivideAndConquer/MaxSubTotal_Naive.py}
    \end{frame}

    %-------------------------------------------------------------------------------

    \begin{frame}{Divide and Conquer}{Example - Maximum Subtotal - Python}
      \textbf{Runtime - Upper bound}
      \onslide<2->
      \vspace{-0.5em}
      \lstinputlisting[
        language=Python,
        basicstyle=\small,
        tabsize=4,
        style={python-idle-code},
        escapechar={@},
        emph={maxSubArray},
        emphstyle=\color{blue}
      ]{Code/DivideAndConquer/MaxSubTotal_Naive_Runtime.py}
    \end{frame}
}

%TODO: Implement for Java / C++

%-------------------------------------------------------------------------------

\begin{frame}{Divide and Conquer}{Example - Maximum Subtotal}
  \textbf{Upper bound:}
  \begin{itemize}
    \item<2->
      Three nested loops
    \item<3->
      Each loop with runtime {\color{MainA}$O(n)$}
    \item<4->
      Algorithm runtime of {\color{MainA}$O(n^3)$}
  \end{itemize}
\end{frame}

%-------------------------------------------------------------------------------

\begin{frame}{Divide and Conquer}{Example - Maximum Subtotal - Runtime}
  \textbf{Lower bound:}
  \begin{table}
    \caption{Operations}
    \label{fig:divide_and_conquer:max_sub_total_operations}
    \begin{tabular}{c|c|c}
      $i$ & Additions & $j$\\
      \midrule
      $\frac{n}{3} \in O(n)$ &
      $\frac{n}{3} \in O(n)$ &
      $\frac{n}{3} \in O(n)$\\
    \end{tabular}
  \end{table}
  \begin{itemize}
    \item<2->
      We iterate at least {\color{MainA}$\frac{n}{3}$} values for {\color{MainA}$i$}
    \item<3->
      For each {\color{MainA}$i$} we iterate at least {\color{MainA}$\frac{n}{3}$} values for {\color{MainA}$j$}
    \item<4->
      For each {\color{MainA}$j$} we have at least {\color{MainA}$\frac{n}{3}$} additions
    \item<5->
      We need at least {\color{MainA}$T(n) = (\frac{n}{3})^3 \in \Omega(n^3)$} steps
  \end{itemize}

\end{frame}

%-------------------------------------------------------------------------------

\begin{frame}{Divide and Conquer}{Example - Maximum Subtotal - Runtime}
  \textbf{Runtime:}
  \begin{itemize}
    \item<2->
      With {\color{MainA}$T(n) \in O(n^3)$} and
      {\color{MainA}$T(n) \in \Omega(n^3)$} we know:
      \begin{displaymath}
        \color{MainA}
        T(n) \in \Theta(n^3)
      \end{displaymath}
    \item<3->
      It is hard to solve the problem in a worse way $\ldots$
  \end{itemize}
\end{frame}

%-------------------------------------------------------------------------------

\begin{frame}{Divide and Conquer}{Example - Maximum Subtotal - Runtime}
  \textbf{Current approach:}
  \begin{itemize}
    \item<2->
      Calculating the sum for range from $i$ to $j$ with loop
      \begin{displaymath}
        S_{i,\,j} = X[i] + X[i+1] + \dots + X[j]
      \end{displaymath}
  \end{itemize}
  \onslide<3->
   \textbf{Better approach:}
   \begin{itemize}
    \item<4->
      Incremental sum instead of loop
      \begin{eqnarray*}
        S_{i,\,j+1} &=& X[i] + X[i+1] + \dots + X[j] + X[j+1]\\
        S_{i,\,j+1} &=& S_{i,\,j} + X[j+1]
        ~{\color{MainA}\in O(1)}\hspace{1em}
          \text{instead of}\hspace{1em} {\color{MainA}\in O(n)}
      \end{eqnarray*}
  \end{itemize}
\end{frame}

%-------------------------------------------------------------------------------

\codeslide{python}{
  \begin{frame}{Divide and Conquer}{Example - Maximum Subtotal - Python}
     \textbf{Better solution:}
     \onslide<2->
  \vspace{-0.5em}
  \lstinputlisting[
    language=Python,
    basicstyle=\small,
    tabsize=4,
    style={python-idle-code},
    escapechar={@},
    emph={maxSubArray},
    emphstyle=\color{blue}
  ]{Code/DivideAndConquer/MaxSubTotal.py}
   \begin{itemize}
   \item<3->Runtime {\color{MainA}$\in O(n^2)$}
   \end{itemize}
\end{frame}
}

%TODO: Implement for Java / C++

%-------------------------------------------------------------------------------

\begin{frame}{Divide and Conquer}{Example - Maximum Subtotal}
  \textbf{Divide and Conquer:}
  \vspace{-1.5em}
  \begin{figure}
    \begin{adjustbox}{width=\linewidth}
      \input{Images/DivideAndConquer/MaxSubTotal_Divide.tikz}
    \end{adjustbox}
    \label{fig:divide_and_conquer:max_sub_total_divide}
  \end{figure}
   \vspace{-1.5em}
\textbf{Divide and Conquer idea to solve:}
  \begin{itemize}
  \item<1->
    Split the sequence in the middle
  \item<2->
    Solve left half of the problem
  \item<3->
    Solve right half and combine both solutions into one
  \item<4->
    Maximum might be located in {\color{MainA}left~half~($A$)}
    or {\color{MainA}right~half~($B$)}
  \item<5->
    Problem: Maximum can {\color{MainA} overlap the split}
  \item<6->
    To solve this case we have to calculate {\color{MainA}rmax}
    and {\color{MainA}lmax}
  \item<7->
    The overall solution is the {\color{MainA}maximum of $A$, $B$ and $C$}
  \end{itemize}
\end{frame}

%-------------------------------------------------------------------------------

\begin{frame}{Divide and Conquer}{Example - Maximum Subtotal}
  \textbf{Principle - Divide and Conquer:}
  \begin{itemize}
    \item<2->
      Small problems are solved directly:
      {\color{MainA}$n = 1 \Rightarrow \max = X[0]$}
    \item<3->
      Bigger problems are partitioned into two subproblems
      and solved recursively.
      Subsolutions {\color{MainA}A} and {\color{MainA}B} are returned
    \item<4->
      To determine subsolution {\color{MainA}C}, {\color{MainA}rmax}
      and {\color{MainA}lmax} for the subproblems are computed
    \item<5->
      The overall solution is the {\color{MainA}maximum of $A$, $B$ and $C$}
  \end{itemize}
\end{frame}

%-------------------------------------------------------------------------------

\codeslide{python}{
  \begin{frame}{Divide and Conquer}{Example - Maximum Subtotal - Python}
  \lstinputlisting[
    language=Python,
    basicstyle=\small,
    tabsize=4,
    style={python-idle-code},
    escapechar={@},
    emph={maxSubArray},
    emphstyle=\color{blue},
    breaklines=false
  ]{Code/DivideAndConquer/MaxSubTotal_DivideAndConquer.py}
\end{frame}
}

%TODO: Implement for Java / C++


\title{Computer Architecture - CS 301} % You may change the title if you want.

\author{Rishit Saiya - 180010027, Assignment - 9}

\date{\today}

\documentclass[12pt]{article}
\usepackage{fullpage}
\usepackage{enumitem}
\usepackage{amsmath,mathtools}
\usepackage{amssymb}
\usepackage[super]{nth}
\usepackage{textcomp}
\usepackage{hyperref}
\begin{document}
\maketitle

%----------------------------------------------------------------
\section{}
Given that our address size is \textbf{32-bit}. Additionally we are given that line size is \textbf{64B} and cache is of size \textbf{1kB}. In this problem, we are supposed to illustrate our approach on how cache will search the address A (32-bit) for 3 various cases namely: Direct Mapped Cache, Fully Associative Cache \& 2-way set Associative Cache.

The Number of Entries (N) will be calculated as follows:
\begin{equation*}
    N = \frac{CS}{LS}
\end{equation*}
where CS is the cache size and LS is the Line Size. \\

In this case, it would be as follows:
\begin{equation*}
    N = \frac{2^{10}}{2^6}
\end{equation*}
or,
\begin{equation*}
    N = 2^4
\end{equation*}
or,
\begin{equation*}
    N = 16
\end{equation*}
We know that definitions of Data array and Tag Array which are contents of block \& a entity of the block address such that the block can be uniquely identified respectively. [Source - Video Lecture].
%----------------------------------------------------------------
\subsection{Direct Mapped Cache}
Before we try to illustrate on approach of Direct Mapped Cache, let's understand about Direct Mapped Cache. \\

In this technique, we map each block of main memory into only one possible cache line. In other words, we assign each memory block to a specific line in the cache.
\begin{verbatim}
  if(Line is taken up prior by a memory block, when loading is done){
      Trash (Old Block);
  }
\end{verbatim}
As main literature suggests, an address space is split into two parts index field \& a tag field. The cache is used to store the tag field whereas the rest is stored in the main memory. However the problem here is that each block can be mapped only to 1 entry only. \\

\begin{table}[]
\begin{center}

\begin{tabular}{|l|c|l|}
\hline
\textbf{Tag (22 bits)} & \textbf{Index (4 bits)} & \textbf{Offset (6 bits)} \\ \hline
\end{tabular}
\caption{Address format for Direct Mapped Cache}
\end{center}
\end{table}
As mentioned in Table 1, Address format is mentioned. We know that in Direct Mapped method, the index is calculated in the following way:
\begin{equation*}
    Index = BA(A) \,  modulo \, N
\end{equation*}
where BA(A) is the Block Address of A and N (16 in this case) is the number of entries. \\

The tag comparison essentially is 22 MSB bits of the address A.
So by that logic, the last 4 bits of the address after removing offset (6 bits), we then access entry, index in the tag array of address and then compare the contents of the tag.
Later we follow the logic:
\begin{verbatim}
     If (match = Hit){
         Hit;
     }
     else{
         Miss;
     }
\end{verbatim}
In this way, the contents are read from the data array of the matching entry.
%----------------------------------------------------------------
\subsection{Fully Associative Cache}
Before we try to illustrate on approach of Direct Mapped Cache, let's understand about Fully Associative Cache. \\

In this technique, the associative memory is used to store content and addresses of the memory word. It means that any block can go into any line of the cache. We use the word id bits to identify which word in the block is needed, but the tag becomes all of the remaining bits in address. This enables the placement of any word at any place in the cache memory.  \\

Some issues which were mentioned in the video were that the tag array consists CAM arrays and they are larger and slower. This is not very power efficient because we need to compare the block address with every single entry on the tag array as mentioned above. Some patches for power issues are mentioned in Razor DVS Technique (seminar topic). \\

\begin{figure}
    \centering
    \includegraphics{Assignment-9/fully_associative_cache.png}
    \caption{Fully Associative Cache}
\end{figure}

Figure 1 shows address format of Fully Associative Cache. Here, according to the concept, we see that Tag has \textbf{26 bits} and Offset is \textbf{6 bits}.

As mentioned in the video, an array of CAM cells is used for the 22 bit long tag array. We follow the below logic (the tag comparison is essentially with 26 MSB of address):
\begin{verbatim}
    Compare entry with Tag;
    Match Line = 1;
\end{verbatim}
It means that each entry would compare its contents with the tag in the above mentioned fashion and the match line is set to 1. Later, the OR gate computes a hit or miss. The encoder mentioned in the lecture then computes the index of the matched entry and in this way, the contents are read from the data array of the matching entry. However we have to note that index will be 4 bits long here because there are 16 entries.
%----------------------------------------------------------------
\subsection{2-way Set Associative Cache}
Before we try to illustrate on approach of Direct Mapped Cache, let's understand about k-way set Associative Cache. \\

In this technique, the set associative addresses the problem of possible thrashing in the direct mapping method. We do this by saying that instead of having exactly one line that a block can map to in the cache, we will group a few lines together creating a set. Then a block in memory can map to any one of the lines of a specific set. So, in the Set-associative mapping, it allows that each word that is present in the cache can have two or more words in the main memory for the same index address. \\

\begin{table}[]
\begin{center}
\begin{tabular}{|l|c|l|}
\hline
\textbf{Tag (23 bits)} & \textbf{Index (3 bits)} & \textbf{Offset (6 bits)} \\ \hline
\end{tabular}
\caption{2-way Set Associative Cache Address Format}
\end{center}
\end{table}

For a k-way association, we divide tag array in sets of k entries. Table 2 shows the address format for the 2-way Set Associative Cache.\\

In this case it is 2. So, we now have a 23 bit long tag array and 3 bit long index in the address. With the same idea as above, we access indices and then read all the tags in the given set. We then compare the tags with the address tag. Later, OR gate is used to compute a hit/miss as above. Then encoder as mentioned in lecture finds the index of the matched entry. It is to be noted that we have 8 indices (obtained by 16/2) where each index pointing to a set of 2 entries in the address.

\section{Conclusion}
This part is written by help of video lecture.

When we try to compare the \textbf{\textit{Speed of Caches}}, we see that Direct Mapped Cache performs the best. It is then followed by k-Set Associative Cache and finally follows Fully Associative Cache. \\

When we try to compare the \textbf{\textit{Hit Rate of Caches}}, we see that Fully Associative Cache performs the best. It is then followed by k-Set Associative Cache and finally follows Direct Mapped Cache. \\

As also given in the lecture, there is this small trade off for choosing the best method of Cache. But as we can see, it is better to safe by choosing K-set Associative Cache as it provides optimum speed and hit rate.
%----------------------------------------------------------------
\end{document}


%% skmath improved math commands
%%
%% Copyright (C) 2012-2019 by Simon Sigurdhsson <sigurdhsson@gmail.com>
%%
%% This work may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License, either version 1.3
%% of this license or (at your option) any later version.
%% The latest version of this license is in
%%   http://www.latex-project.org/lppl.txt
%% and version 1.3 or later is part of all distributions of LaTeX
%% version 2005/12/01 or later.
%%
%% This work has the LPPL maintenance status `maintained'.
%%
%% The Current Maintainer of this work is Simon Sigurdhsson.
%%
%% This work consists of the file skmath.tex
%% and the derived file skmath.sty.
\PassOptionsToPackage{intlimits,sumlimits,namelimits}{amsmath}
\documentclass[commonsets,load]{skdoc}
\usepackage{amsmath}
\usepackage{csquotes}
\ProvideDocumentCommand\d{m}{#1}
\ProvideDocumentCommand\pd{smm}{#2#3}
\ProvideDocumentCommand\td{mm}{#1#2}
\ProvideDocumentCommand\abs{m}{#1}
\ProvideDocumentCommand\norm{m}{#1}
\ProvideDocumentCommand\abs{m}{#1}
\ProvideDocumentCommand\P{m}{#1}
\ProvideDocumentCommand\given{}{}
\ProvideDocumentCommand\E{m}{#1}
\ProvideDocumentCommand\var{m}{#1}
\ProvideDocumentCommand\cov{mm}{#1#2}
\ProvideDocumentCommand\N{}{}
\ProvideDocumentCommand\Z{}{}
\ProvideDocumentCommand\Q{}{}
\ProvideDocumentCommand\R{}{}
\ProvideDocumentCommand\C{}{}
\ProvideDocumentCommand\ii{}{i}
\ProvideDocumentCommand\jj{}{j}
\ProvideDocumentCommand\ee{}{e}
\ProvideDocumentCommand\sfrac{mm}{#1#2}
\ProvideDocumentCommand\argmin{om}{#1}
\ProvideDocumentCommand\argmax{om}{#1}

% Declare the target files
\SelfPreambleTo{\mypreamble}
\DeclareFile[key=package,preamble=\mypreamble]{skmath.sty}
\OnlyDescription

% Hack for LaTeX3 code
\ExplSyntaxOn
\cs_set_protected_nopar:Npn\ExplHack{
\char_set_catcode_letter:n{ 58 }
\char_set_catcode_letter:n{ 95 } }
\ExplSyntaxOff

% This is where the documentation begins
\begin{document}
  % Change & version info
  \version{0.5a}
  \changes{0.1}{Initial version}
  \changes{0.1c}{Moved package from \pkg{docstrip} to \pkg{skdoc}}
  \changes{0.1d}{Fixed fatal documentation and package errors}
  \changes{0.1e}{Added statistics commands}
  \changes{0.1g}{Documentation fixes}
  \changes{0.2}{Use \pkg{expl3} functionality throughout the package}
  \changes{0.3}{Added \cs{min}/\cs{max} and friends. Added \cs{pd}}
  \changes{0.3a}{Added \cs{sinh}, \cs{cosh} and \cs{tanh}}
  \changes{0.3b}{Detect empty arguments in trigonometric and logarithmic functions, fix \cs{ln}}
  \changes{0.4}{Added \opt{notation} option, macros for complex numbers}
  \changes{0.4a}{Replaced deprecated/removed \pkg{expl3} constructs}
  \changes{0.4b}{Track \pkg{expl3} changes (thanks to Joseph Wright)}
  \changes{0.5}{Added \cs{td} and \cs{ee}}
  \changes{0.5a}{Track \pkg{expl3} changes (thanks to Phelype Oleinik)}
  % Don't forget to update the version number and release date of
  % the package declaration in the implementation!

  % Metadata
  \package[ctan=skmath,vcs=https://github.com/urdh/skmath]{skmath}
  \author{Simon Sigurdhsson}
  \email{sigurdhsson@gmail.com}

  % First page
  \maketitle
  \begin{abstract}
    The \thepackage\ package provides improved and new math commands
    for superior typesetting with less effort.
  \end{abstract}

  \section{Introduction}
  This package intends to provide helpful (re-)definitions of commands
  related to typesetting mathematics, and specifically typesetting
  them in a more intuitive, less verbose and more beautiful way.
  It was originally not intended for use by the public, and as such
  there may be incompatibilities with other packages of which I am
  not aware, but I figured it could be useful to other people as well.

  \section{Usage}
  \subsection{Options}
  As of version \theversion, the package provides two key-value options.

  \Option{commonsets}\WithValues{true,false}\AndDefault{false}
  Optionally define \cs{N}, \cs{Z}, \cs{Q}, \cs{R} and \cs{C} as blackboard
  variants of the respective letters, to represent the common sets
  of numbers.

  \Option{notation}\WithValues{iso,english,german,legacy}\AndDefault{legacy}
  This option controls the style of a few typographic elements that differ
  between countries and standards (such as the style of integrals, derivatives
  and greek letters).

  \subsection{New commands}
  The package defines a number of new commands that aid in typesetting
  certain mathematical formulae.

  \DescribeMacro\N
  \DescribeMacro\Z
  \DescribeMacro\Q
  \DescribeMacro\R
  \DescribeMacro\C
  These commands are only available if the \opt{commonsets}
  option is given. They typeset the set of natural, integer, rational,
  real and complex numbers respectively.
\begin{example}
\begin{equation*}
  \N, \Z, \Q, \R, \C.
\end{equation*}
\end{example}

  \DescribeMacro\ii
  \DescribeMacro\jj
  These commands typeset the imaginary unit (either \(\ii\) as used in
  mathematics or \(\jj\) as used in electrotechnology). While normal use
  of the package simply results in italic characters, setting the \opt{notation}
  option to \texttt{iso} will set these upright.

  \DescribeMacro\ee
  This command typesets Euler's number \(\ee = \sum_{n=0}^\infty\frac{1}{n!}\).
  The style is affected by the \opt{notation} option in the same way as \Macro\exp.

  \DescribeMacro\norm{<expression>}
  \DescribeMacro\abs{<expression>}
  The commands \Macro\norm and \Macro\abs, quite expectedly, typeset
  the norm ans absolute value of an expression, respectively. They
  have one mandatory argument (the expression), and different norms
  can be achieved by appending a subscript after the argument of
  \Macro\norm.
\begin{example}
\begin{equation*}
  \norm{\vec{x}}_p =
    \left(\sum_{i=1}^n \abs{x_i}^p\right)%
      ^{\sfrac{1}{p}}
\end{equation*}
\end{example}

  \DescribeMacro\d{<variable>}
  There is also a command \Macro\d, with one mandatory argument, that
  typesets the differential part of an integral.
\begin{example}
\begin{equation*}
  \int_{\R}\! \frac{\sin{x}}{x} \d{x}
\end{equation*}
\end{example}

  \DescribeMacro\pd*{<function>}{<var>,\meta{var},...}
  This macro typesets a partial derivative. The starred variant typesets
  derivatives as subscripts, i.e. \(\pd*{f}{x^2,y}\), while the unstarred
  variant typesets full fractions:
\begin{example}
\begin{equation*}
  \pd{f}{x^m,y^n}
\end{equation*}
\end{example}

  As the example shows, the comma-separated list of variables also
  supports superscripts to denote the number of derivatives, and the
  sum of the variables is automatically calculated.

  \DescribeMacro\td{<function>}{<var>}
  This macro typesets a total derivative. Unlike \Macro\pd, this macro does
  not have a starred variant, and only typesets full fractions:
\begin{example}
\begin{equation*}
  \td{f}{x^m}
\end{equation*}
\end{example}

  \DescribeMacro\E{<expression>}
  The command \Macro\E typesets the expectation of a random variable.
\begin{example}
\begin{equation*}
  \E{\hat{\mu}} = \mu
\end{equation*}
\end{example}

  \DescribeMacro\P{<expression>\AlsoMacro\given <expression>}
  The \Macro\P command typesets a probability. The \Macro\given command
  can be used to typeset conditional probabilities, within \Macro\P.
\begin{example}
\begin{equation*}
  \P{A\given B} =
    \frac{\P{B\given A}\P{A}}{\P{B}}
\end{equation*}
\end{example}

  \DescribeMacro\var{<expression>}
  \DescribeMacro\cov{<expression>}{<expression>}
  The commands \Macro\var and \Macro\cov typeset the variance and
  covariance of an expression.
\begin{example}
\begin{gather*}
  \var{X} = \E{(X-\mu)^2}\\
  \cov{X}{Y} = \E{XY}-\E{X}\E{Y}
\end{gather*}
\end{example}

  \subsection{Improved commands}
  In addition to adding new commands, this package also redefines
  already existing commands in a mostly backwards-compatible way
  to improve their usefulness.

  \DescribeMacro\sin[<power>]{<expression>}
  \DescribeMacro\arcsin{<expression>}
  \DescribeMacro\cos[<power>]{<expression>}
  \DescribeMacro\arccos{<expression>}
  \DescribeMacro\tan[<power>]{<expression>}
  \DescribeMacro\arctan{<expression>}
  \DescribeMacro\cot[<power>]{<expression>}
  \DescribeMacro\sinh[<power>]{<expression>}
  \DescribeMacro\cosh[<power>]{<expression>}
  \DescribeMacro\tanh[<power>]{<expression>}
  The trigonometric functions have been redefined
  to typeset more easily. They typeset \meta{expression} as an
  argument of the expression, and (if applicable) \meta{power} as
  a superscript between the function and its argument,
  \emph{e.g.} \(\sin[2]{\phi}\).
  When the argument is empty, no parentheses are emitted: \(\cos{}\).

  \DescribeMacro\ln{<expression>}
  The natural logarithm macro \Macro\ln has also been redefined to
  require an argument which is typeset as the argument of the logarithm.
  \DescribeMacro\log[<base>]{<expression>}
  The related macro \Macro\log is redefined in a similar way, but also
  accepts an optional argument denoting the base of the logarithm:
  \(\log[2]{x}\).
  As with the trigonometric functions, no parentheses are emitted if
  the mandatory argument is empty: \(\log{}\).

  \DescribeMacro\exp*{<expression>}
  The exponential, \Macro\exp, is redefined to typeset its argument as a
  superscript of \(\ee\) in some display styles, and as an argument of
  \(\mathrm{exp}\) otherwise:
  \begin{equation*}
    \exp{\sqrt{2}\exp{x}}
  \end{equation*}
  Additionally, it is possible to force the \(\mathrm{exp}\) mode by
  using the starred variant.

  \DescribeMacro\min*[<domain>]{<expression>}
  \DescribeMacro\argmin*[<domain>]{<expression>}
  \DescribeMacro\max*[<domain>]{<expression>}
  \DescribeMacro\argmax*[<domain>]{<expression>}
  \DescribeMacro\sup*[<domain>]{<expression>}
  \DescribeMacro\inf*[<domain>]{<expression>}
  The maximum/minimum macros have been redefined in a manner similar to
  the trigonometric functions. They typeset \meta{expression} inside
  curly brackets (the starred version omits the brackets), with the
  optional \meta{domain} typeset in a subscript after the operator
  (\emph{e.g.} \(\min*[x\in\R_{+}]{f(x)}\)). Argument variants are also
  provided, and the \meta{expression} is centered underneath the operator
  if possible:
  \begin{equation*}
    \argmin*[x\in\R_{+}]{f(x)}
  \end{equation*}

  \subsection{Stylistic changes}
  Some commands have been redefined in a completely backwards-compatible
  way to improve the end result of their typesetting.

  \DescribeMacro\frac{<numerator>}{<denominator>}
  The \Macro\frac command has been changed to improve typesetting,
  allowing displaystyle math in some settings.

  \DescribeMacro\bar{<expression>}
  \DescribeMacro\vec{<expression>}
  The \Macro\bar command has been changed to cover the entire
  \meta{expression} (\emph{i.e.} \(\bar{uv}\)), and \Macro\vec has
  been changed to match the \cs{vectorsym} command provided by
  \pkg{isomath}.

  \DescribeMacro\Re{<expression>}
  \DescribeMacro\Im{<expression>}
  These commands typeset the real and imaginary part of a number. Standard use
  of the package takes definitions roughly from \pkg{amsmath}, while setting
  the \opt{notation} option to \texttt{iso} changes the definitions to match
  ISO~80000-2.

  \section{Known issues}
  A list of current issues is available in the Github repository of this
  package\footnote{\url{https://github.com/urdh/skmath/issues}}, but as
  of the release of \theversion, there is one known issue.
  \begin{description}
      \item[\#15] The package is incompatible with (at least)
        \pkg{blindtext}, when including math in the blind text. This
        is due to the redifinition of \cs{sin} (and friends), which
        is incompatible with the original \pkg{amsmath} definition.
        This is a feature, not a bug.
      \item[\#29] The spacing between operator names and parentheses
        is typographically incorrect. A work-around until this is
        fixed in \pkg{skmath} is to use the \cs{mleftright} macro from
        \pkg{mleftright} to redefine \cs{left} and \cs{right}.
  \end{description}

  If you discover any bugs in this package, please report them to the issue
  tracker in the \thepackage\ Github repository.

  \Implementation\ExplHack
  \section{Implementation}
  The package implementation is very simple. First, we do the standard
  \LaTeXe\ preamble thing, then we require some dependencies.
  \changes{0.1b}{Load \pkg{amsmath} with \texttt{intlimits} option}
  \changes{0.2a}{Load \pkg{amsmath} with more \texttt{limits} options}
\begin{MacroCode}{package}
\RequirePackage{expl3,l3keys2e,xparse}
\ProvidesExplPackage{skmath}
    {2019/10/15}{0.5a}{improved math commands}
\PassOptionsToPackage{intlimits,sumlimits,namelimits}{amsmath}
\RequirePackage{amssymb,mathtools,xfrac}
\end{MacroCode}

We start by declaring internal options related to the notation styles.
First, some placeholders to detect failures.
\begin{MacroCode}{package}
\msg_new:nnnn{skmath}{undefined-macro}{The~macro~`\token_to_str:N#1'~was~undefined!}
  {This~is~an~error~in~the~notation~option~handling.~Please~file~an~issue\\
   on~Github~(https://github.com/urdh/skmath/issues)~with~a~copy~of~this\\
   message~attached~as~well~as~a~list~of~the~options~passed~to~`skmath'.}
\cs_gset_nopar:Npn\__skmath_integral_d:{
  \msg_critical:nnn{skmath}{undefined-macro}{\__skmath_integral_d:}
}
\cs_gset_nopar:Npn\__skmath_natural_log_e:{
  \msg_critical:nnn{skmath}{undefined-macro}{\__skmath_natural_log_e:}
}
\cs_gset_nopar:Npn\__skmath_imaginary_unit:n#1{
  \msg_critical:nnn{skmath}{undefined-macro}{\__skmath_imaginary_unit:n}
}
\cs_gset_nopar:Npn\__skmath_total_derivative_d:{
  \msg_critical:nnn{skmath}{undefined-macro}{\__skmath_total_derivative_d:n}
}
\end{MacroCode}
Then, the key-value options.
\begin{MacroCode}{package}
\keys_define:nn{skmath / internal}{
  % More on this:
  % * http://en.wikipedia.org/wiki/Typographical_conventions_in_mathematical_formulae
  % * ISO 80000-2
  % * http://www.tug.org/TUGboat/Articles/tb18-1/tb54becc.pdf
  % * http://tex.stackexchange.com/q/14821/66
  integral-d .choice:,
  integral-d .value_required:n = true,
  integral-d / upright .code:n = { \cs_gset_nopar:Npn\__skmath_integral_d:{{\operator@font d}} },
  integral-d / slanted .code:n = { \cs_gset_nopar:Npn\__skmath_integral_d:{{d}} },
  isomath .bool_set:N = \g__skmath_load_isomath_bool,
  isomath .value_required:n = true,
  natural-log .choice:,
  natural-log .value_required:n = true,
  natural-log / upright .code:n = { \cs_gset_nopar:Npn\__skmath_natural_log_e:{{\operator@font e}} },
  natural-log / slanted .code:n = { \cs_gset_nopar:Npn\__skmath_natural_log_e:{{e}} },
  imaginary-unit .choice:,
  imaginary-unit .value_required:n = true,
  imaginary-unit / upright .code:n = { \cs_gset_nopar:Npn\__skmath_imaginary_unit:n##1{{\operator@font ##1}} },
  imaginary-unit / slanted .code:n = { \cs_gset_nopar:Npn\__skmath_imaginary_unit:n##1{{##1}} },
  complex-part-symbols .bool_set_inverse:N = \g__skmath_iso_complex_parts_bool,
  complex-part-symbols .value_required:n = true,
  total-derivative-d .choice:,
  total-derivative-d .value_required:n = true,
  total-derivative-d / upright .code:n = { \cs_gset_nopar:Npn\__skmath_total_derivative_d:{{\operator@font d}} },
  total-derivative-d / slanted .code:n = { \cs_gset_nopar:Npn\__skmath_total_derivative_d:{{d}} },
}
\end{MacroCode}

We also declare the \enquote{public} options.
\begin{MacroCode}{package}
\keys_define:nn{skmath}{
  commonsets .bool_set:N = \g__skmath_define_common_sets_bool,
  commonsets .default:n = true,
  commonsets .initial:n = false,
  % TODO: write tests for the notation option
  notation .choice:,
  notation / iso .meta:nn = {skmath / internal}{
    integral-d = upright,
    isomath    = true,
    natural-log = upright,
    imaginary-unit = upright,
    complex-part-symbols = false,
    total-derivative-d = upright,
  },
  notation / german .meta:nn = {skmath / internal}{
    integral-d = upright,
    isomath    = true,
    natural-log = slanted, %???
    imaginary-unit = slanted, %???
    complex-part-symbols = true, %???
    total-derivative-d = upright, %???
  },
  notation / english .meta:nn = {skmath / internal}{
    integral-d = slanted,
    isomath    = true,
    natural-log = slanted, %???
    imaginary-unit = slanted, %???
    complex-part-symbols = true, %???
    total-derivative-d = slanted, %???
  },
  notation / legacy .meta:nn = {skmath / internal}{
    integral-d = upright,
    isomath    = true,
    natural-log = slanted,
    imaginary-unit = slanted,
    complex-part-symbols = true,
    total-derivative-d = slanted,
  },
  % Possibly more style sets... ?
  notation .initial:n = legacy, % Or is it? Perhaps a legacy option is required.
  notation .value_required:n = true,
  % Note also that the styles should probably affect isomath and/or other packages.
}
\ProcessKeysOptions{skmath}
\end{MacroCode}

We optionally load \pkg{isomath}, depending on notation style.
\begin{MacroCode}{package}
\bool_if:NTF\g__skmath_load_isomath_bool{
  \RequirePackage{isomath}
}{
  % TODO: check if there is an alternative package we should load here.
}
\end{MacroCode}

  Then, a utility conditional\ldots
  \begin{macro*}{\__skmath_if_novalue_or_empty:nF}[1]
    {Token or string}
\begin{MacroCode}{package}
\prg_new_conditional:Npnn\__skmath_if_novalue_or_empty:n#1{F}{
  \IfNoValueTF{#1}{
    \prg_return_true:
  }{
    \tl_if_empty:nTF{#1}{
      \prg_return_true:
    }{
      \prg_return_false:
    }
  }
}
\end{MacroCode}
  \end{macro*}

  \ldots and a helper macro.
  \begin{macro*}{\__skmath_parens:n}[1]
    {Argument to wrap in parentheses, unless empty}
\begin{MacroCode}{package}
\cs_new_nopar:Npn\__skmath_parens:n#1{
  \__skmath_if_novalue_or_empty:nF{#1}{\left(#1\right)}
}
\end{MacroCode}
  \end{macro*}

  We optionally provide commands to typeset common sets.
\begin{MacroCode}{package}
\bool_if:NT\g__skmath_define_common_sets_bool{
\end{MacroCode}
  \begin{macro}{\N}
  \changes{0.1b}{Moved to \textsf{xparse} command definition}
\begin{MacroCode}{package}
  \NewDocumentCommand\N{}{\ensuremath{\mathbb{N}}}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\Z}
  \changes{0.1b}{Moved to \textsf{xparse} command definition}
\begin{MacroCode}{package}
  \NewDocumentCommand\Z{}{\ensuremath{\mathbb{Z}}}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\Q}
  \changes{0.1b}{Moved to \textsf{xparse} command definition}
\begin{MacroCode}{package}
  \NewDocumentCommand\Q{}{\ensuremath{\mathbb{Q}}}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\R}
  \changes{0.1b}{Moved to \textsf{xparse} command definition}
\begin{MacroCode}{package}
  \NewDocumentCommand\R{}{\ensuremath{\mathbb{R}}}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\C}
  \changes{0.1b}{Moved to \textsf{xparse} command definition}
\begin{MacroCode}{package}
  \NewDocumentCommand\C{}{\ensuremath{\mathbb{C}}}
\end{MacroCode}
  \end{macro}
\begin{MacroCode}{package}
}
\end{MacroCode}

  Then, macros related to complex numbers are defined.
  \begin{macro}{\ii}
\begin{MacroCode}{package}
\DeclareDocumentCommand\ii{}{\ensuremath{\__skmath_imaginary_unit:n{i}}}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\jj}
\begin{MacroCode}{package}
\DeclareDocumentCommand\jj{}{\ensuremath{\__skmath_imaginary_unit:n{j}}}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\Re}
\begin{MacroCode}{package}
\bool_if:NTF\g__skmath_iso_complex_parts_bool{
  \cs_new_eq:NN\__skmath_Re:\Re
  \DeclareDocumentCommand\Re{m}{\ensuremath{\__skmath_Re:\__skmath_parens:n{#1}}}
}{
  \DeclareDocumentCommand\Re{m}{\ensuremath{{\operator@font Re}{#1}}}
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\Im}
\begin{MacroCode}{package}
\bool_if:NTF\g__skmath_iso_complex_parts_bool{
  \cs_new_eq:NN\__skmath_Im:\Im
  \DeclareDocumentCommand\Im{m}{\ensuremath{\__skmath_Im:\__skmath_parens:n{#1}}}
}{
  \DeclareDocumentCommand\Im{m}{\ensuremath{{\operator@font Im}{#1}}}
}
\end{MacroCode}
  \end{macro}

  This is followed by commands to typeset the norm and absolute value.
  \begin{macro}{\abs}
\begin{MacroCode}{package}
\DeclarePairedDelimiter\abs{\lvert}{\rvert}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\norm}
\begin{MacroCode}{package}
\DeclarePairedDelimiter\norm{\lVert}{\rVert}
\end{MacroCode}
  \end{macro}

  Next come the statistical commands.
  \begin{macro}{\E}
  \changes{0.1e}{Added \cs{E} command}
  \changes{0.1f}{Fixed \enquote{Command \cs{E} already defined!} error}
  \changes{0.2}{Use \cs{operatorname}}
  Here, we define \cs{E} after the preamble since it may break otherwise.
\begin{MacroCode}{package}
\AtBeginDocument{
  \DeclareDocumentCommand\E{m}{%
    \ensuremath{\operatorname{E}\left[#1\right]}%
  }
}
\end{MacroCode}
  \end{macro}
  The \Macro\P command saves any old \Macro\given command, replacing
  it locally with the new \Macro\given command provided by the package.
  \begin{macro}{\P}
  \changes{0.1e}{Added \cs{P} command}
  \changes{0.2}{Use \cs{operatorname}, use \cs{cs_new_eq:NN} instead of
                \cs{let}}
\begin{MacroCode}{package}
\DeclareDocumentCommand\P{m}{%
  \ensuremath{\operatorname{P}%
    \mkern-1.5mu\left(%
    \cs_set_eq:NN\__skmath_saved_given:\given%
\end{MacroCode}
  \begin{macro}{\given}
  \changes{0.1e}{Added \cs{given} command}
\begin{MacroCode}{package}
    \DeclareDocumentCommand\given{}{\mid}%
\end{MacroCode}
  \end{macro}
\begin{MacroCode}{package}
    #1%
    \cs_set_eq:NN\given\__skmath_saved_given:%
    \right)%
  }%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\var}
  \changes{0.1e}{Added \cs{var} command}
  \changes{0.2}{Use \cs{operatorname}}
\begin{MacroCode}{package}
\DeclareDocumentCommand\var{m}{%
  \ensuremath{\operatorname{Var}\left(#1\right)}%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\cov}
  \changes{0.1e}{Added \cs{cov} command}
  \changes{0.2}{Use \cs{operatorname}}
\begin{MacroCode}{package}
\DeclareDocumentCommand\cov{mm}{%
  \ensuremath{\operatorname{Cov}\left(#1,#2\right)}%
}
\end{MacroCode}
  \end{macro}

  We replace all trigonometric functions and some other
  common functions with alternatives that take an argument
  (or optionally, several arguments).
\begin{MacroCode}{package}
\cs_new_eq:NN\__skmath_sin:\sin
\cs_new_eq:NN\__skmath_cos:\cos
\cs_new_eq:NN\__skmath_tan:\tan
\cs_new_eq:NN\__skmath_cot:\cot
\cs_new_eq:NN\__skmath_arcsin:\arcsin
\cs_new_eq:NN\__skmath_arccos:\arccos
\cs_new_eq:NN\__skmath_arctan:\arctan
\cs_new_eq:NN\__skmath_sinh:\sinh
\cs_new_eq:NN\__skmath_cosh:\cosh
\cs_new_eq:NN\__skmath_tanh:\tanh
\cs_new_eq:NN\__skmath_ln:\ln
\cs_new_eq:NN\__skmath_log:\log
\cs_new_eq:NN\__skmath_exp:\exp
\cs_new_eq:NN\__skmath_min:\min
\cs_new_eq:NN\__skmath_max:\max
\cs_new_eq:NN\__skmath_sup:\sup
\cs_new_eq:NN\__skmath_inf:\inf
\end{MacroCode}
  \begin{macro}{\sin}
\begin{MacroCode}{package}
\RenewDocumentCommand\sin{om}{%
  \IfNoValueTF{#1}
    {\ensuremath{\__skmath_sin:\__skmath_parens:n{#2}}}
    {\ensuremath{\__skmath_sin:\c_math_superscript_token{#1}\__skmath_parens:n{#2}}}%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\cos}
\begin{MacroCode}{package}
\RenewDocumentCommand\cos{om}{%
  \IfNoValueTF{#1}
    {\ensuremath{\__skmath_cos:\__skmath_parens:n{#2}}}
    {\ensuremath{\__skmath_cos:\c_math_superscript_token{#1}\__skmath_parens:n{#2}}}%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\tan}
\begin{MacroCode}{package}
\RenewDocumentCommand\tan{om}{%
  \IfNoValueTF{#1}
    {\ensuremath{\__skmath_tan:\__skmath_parens:n{#2}}}
    {\ensuremath{\__skmath_tan:\c_math_superscript_token{#1}\__skmath_parens:n{#2}}}%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\cot}
\begin{MacroCode}{package}
\RenewDocumentCommand\cot{om}{%
  \IfNoValueTF{#1}
    {\ensuremath{\__skmath_cot:\__skmath_parens:n{#2}}}
    {\ensuremath{\__skmath_cot:\c_math_superscript_token{#1}\__skmath_parens:n{#2}}}%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\arcsin}
\begin{MacroCode}{package}
\RenewDocumentCommand\arcsin{m}{%
  \ensuremath{\__skmath_arcsin:\__skmath_parens:n{#1}}%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\arccos}
\begin{MacroCode}{package}
\RenewDocumentCommand\arccos{m}{%
  \ensuremath{\__skmath_arccos:\__skmath_parens:n{#1}}%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\arctan}
\begin{MacroCode}{package}
\RenewDocumentCommand\arctan{m}{%
  \ensuremath{\__skmath_arctan:\__skmath_parens:n{#1}}%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\sinh}
\begin{MacroCode}{package}
\RenewDocumentCommand\sinh{om}{%
  \IfNoValueTF{#1}
    {\ensuremath{\__skmath_sinh:\__skmath_parens:n{#2}}}
    {\ensuremath{\__skmath_sinh:\c_math_superscript_token{#1}\__skmath_parens:n{#2}}}%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\cosh}
\begin{MacroCode}{package}
\RenewDocumentCommand\cosh{om}{%
  \IfNoValueTF{#1}
    {\ensuremath{\__skmath_cosh:\__skmath_parens:n{#2}}}
    {\ensuremath{\__skmath_cosh:\c_math_superscript_token{#1}\__skmath_parens:n{#2}}}%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\tanh}
\begin{MacroCode}{package}
\RenewDocumentCommand\tanh{om}{%
  \IfNoValueTF{#1}
    {\ensuremath{\__skmath_tanh:\__skmath_parens:n{#2}}}
    {\ensuremath{\__skmath_tanh:\c_math_superscript_token{#1}\__skmath_parens:n{#2}}}%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\ln}
\begin{MacroCode}{package}
\RenewDocumentCommand\ln{m}{%
  \ensuremath{\__skmath_ln:\__skmath_parens:n{#1}}%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\log}
\begin{MacroCode}{package}
\RenewDocumentCommand\log{om}{%
  \IfNoValueTF{#1}
    {\ensuremath{\__skmath_log:\__skmath_parens:n{#2}}}
    {\ensuremath{\__skmath_log:\c_math_subscript_token{#1}\__skmath_parens:n{#2}}}%
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\ee}
    \begin{MacroCode}{package}
    \DeclareDocumentCommand\ee{}{\ensuremath{\__skmath_natural_log_e:}}
    \end{MacroCode}
  \end{macro}
  \begin{macro}{\exp}
  \changes{0.1b}{Moved to \textsf{xparse} command definition}
  \changes{0.3a}{Added starred variant}
\begin{MacroCode}{package}
\RenewDocumentCommand\exp{sm}{\ensuremath{
  \IfBooleanTF{#1}{
    \__skmath_exp:\__skmath_parens:n{#2}
  }{
    \mathchoice
      {\__skmath_natural_log_e:\c_math_superscript_token{#2}}
      {\__skmath_exp:\left(#2\right)}
      {\__skmath_exp:\left(#2\right)}
      {\__skmath_exp:\left(#2\right)}
  }
}}
\end{MacroCode}
  \end{macro}
  \begin{macro*}{\__skmath_minmax_backend:nnn}
\begin{MacroCode}{package}
\cs_new_nopar:Npn\__skmath_minmax_backend:nnnn#1#2#3#4{%
  \use:c{__skmath_#1:}
  \IfNoValueF{#3}{
    \c_math_subscript_token{
      \mathchoice{\mathclap{#3}}{#3}{#3}{#3}
    }
  }
  \IfBooleanTF{#2}{#4}{\left\{#4\right\}}
}
\end{MacroCode}
  \end{macro*}
  \begin{macro}{\min}
\begin{MacroCode}{package}
\RenewDocumentCommand\min{som}{%
  \ensuremath{\__skmath_minmax_backend:nnnn{min}{#1}{#2}{#3}}
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\argmin}
\begin{MacroCode}{package}
\NewDocumentCommand\argmin{som}{%
  \ensuremath{\arg\__skmath_minmax_backend:nnnn{min}{#1}{#2}{#3}}
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\max}
\begin{MacroCode}{package}
\RenewDocumentCommand\max{som}{%
  \ensuremath{\__skmath_minmax_backend:nnnn{max}{#1}{#2}{#3}}
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\argmax}
\begin{MacroCode}{package}
\NewDocumentCommand\argmax{som}{%
  \ensuremath{\arg\__skmath_minmax_backend:nnnn{max}{#1}{#2}{#3}}
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\sup}
\begin{MacroCode}{package}
\RenewDocumentCommand\sup{som}{%
  \ensuremath{\__skmath_minmax_backend:nnnn{sup}{#1}{#2}{#3}}
}
\end{MacroCode}
  \end{macro}
  \begin{macro}{\inf}
\begin{MacroCode}{package}
\RenewDocumentCommand\inf{som}{%
  \ensuremath{\__skmath_minmax_backend:nnnn{inf}{#1}{#2}{#3}}
}
\end{MacroCode}
  \end{macro}

  The fraction command is modified to improve typesetting.
  \begin{macro}{\frac}
  \changes{0.1b}{Moved to \textsf{xparse} command definition}
\begin{MacroCode}{package}
\RenewDocumentCommand\frac{mm}{\genfrac{}{}{}{}%
             {\displaystyle #1}{\displaystyle #2}}
\end{MacroCode}
  \end{macro}

  We introduce a couple of helper macros for \cs{pd} and \cs{td}.
  \begin{macro*}{\__skmath_if_numerical_p:n}
  \begin{macro*}{\__skmath_if_numerical:nT}
  \begin{macro*}{\__skmath_if_numerical:nF}
  \begin{macro*}{\__skmath_if_numerical:nTF}[1]
    {Token or string}
\begin{MacroCode}{package}
\prg_new_conditional:Npnn\__skmath_if_numerical:n#1{p,T,F,TF}{
  \str_case_e:nnTF{#1}{
    {0}{}
    {1}{}
    {2}{}
    {3}{}
    {4}{}
    {5}{}
    {6}{}
    {7}{}
    {8}{}
    {9}{}
  }
  {\prg_return_false:}
  {\prg_return_false:}
}
\end{MacroCode}
  \end{macro*}
  \end{macro*}
  \end{macro*}
  \end{macro*}
  \begin{macro*}{\__skmath_pd_vars_sum:n}[1]
    {Comma-separated list of variables, possibly with superscripts}
\begin{MacroCode}{package}
\cs_new_nopar:Npn\__skmath_pd_vars_sum:n#1{
  \tl_clear:N\l_tmpa_tl
  \int_zero:N\l_tmpa_int
  \bool_set_true:N\l_tmpa_bool
  \clist_set:Nn\l_tmpa_clist{#1}
  \clist_map_inline:Nn\l_tmpa_clist{
    \seq_set_split:Nnn\l_tmpa_seq{^}{##1}
    \int_compare:nT{\seq_count:N\l_tmpa_seq<2}{
      \seq_put_right:Nn\l_tmpa_seq{1}
    }
    \seq_get_right:NN\l_tmpa_seq\l_tmpb_tl
    \__skmath_if_numerical:nTF{\tl_use:N\l_tmpb_tl}{
      \int_add:Nn\l_tmpa_int{\tl_use:N\l_tmpb_tl}
    }{
      \bool_set_false:N\l_tmpa_bool
      \tl_if_empty:NF\l_tmpa_tl{\tl_put_right:Nn\l_tmpa_tl{+}}
      \tl_put_right:Nx\l_tmpa_tl{\tl_use:N\l_tmpb_tl}
    }
  }
  \int_compare:nT{\l_tmpa_int>\c_zero_int}{\int_use:N\l_tmpa_int}
  \bool_if:NF\l_tmpa_bool{
    \int_compare:nT{\l_tmpa_int>\c_zero_int}{+}
    \tl_use:N\l_tmpa_tl
  }
}
\end{MacroCode}
  \end{macro*}
  \begin{macro*}{\__skmath_pd_if_vars_sum_above_one_p:n}
  \begin{macro*}{\__skmath_pd_if_vars_sum_above_one:nT}
  \begin{macro*}{\__skmath_pd_if_vars_sum_above_one:nF}
  \begin{macro*}{\__skmath_pd_if_vars_sum_above_one:nTF}[1]
    {Comma-separated list of variables, possibly with superscripts}
\begin{MacroCode}{package}
\prg_new_conditional:Npnn\__skmath_pd_if_vars_sum_above_one:n#1{p,T,F,TF}{
  \clist_set:Nn\l_tmpa_clist{#1}
  \int_compare:nTF{\clist_count:N\l_tmpa_clist>\c_one_int}{
    \prg_return_true:
  }{
    \clist_pop:NN\l_tmpa_clist\l_tmpa_tl
    \seq_set_split:NnV\l_tmpa_seq{^}{\l_tmpa_tl}
    \int_compare:nTF{\seq_count:N\l_tmpa_seq<2}{
      \prg_return_false:
    }{
      \prg_return_true:
    }
  }
}
\end{MacroCode}
  \end{macro*}
  \end{macro*}
  \end{macro*}
  \end{macro*}
  \begin{macro*}{\__skmath_pd_superscript_vars:n}[1]
    {Comma-separated list of variables, possibly with superscripts}
\begin{MacroCode}{package}
\cs_new_nopar:Npn\__skmath_pd_superscript_vars:n#1{
  \clist_set:Nn\l_tmpa_clist{#1}
  \clist_map_inline:Nn\l_tmpa_clist{
    \partial
    \seq_set_split:Nnn\l_tmpa_seq{^}{##1}
    \seq_pop:NN\l_tmpa_seq\l_tmpb_tl
    \tl_use:N\l_tmpb_tl
    \int_compare:nT{\seq_count:N\l_tmpa_seq>0}{
      \seq_pop:NN\l_tmpa_seq\l_tmpb_tl
      \c_math_superscript_token
      \tl_use:N\l_tmpb_tl
    }
  }
}
\end{MacroCode}
  \end{macro*}
  \begin{macro*}{\__skmath_pd_subscript_vars:n}[1]
    {Comma-separated list of variables, possibly with superscripts}
\begin{MacroCode}{package}
\cs_new_nopar:Npn\__skmath_pd_subscript_vars:n#1{
  \clist_set:Nn\l_tmpa_clist{#1}
  \clist_map_inline:Nn\l_tmpa_clist{
    \seq_set_split:Nnn\l_tmpa_seq{^}{##1}
    \seq_pop:NN\l_tmpa_seq\l_tmpa_tl
    \int_set:Nn\l_tmpa_int{\c_one_int}
    \int_compare:nT{\seq_count:N\l_tmpa_seq>\c_zero_int}{
      \seq_pop:NN\l_tmpa_seq\l_tmpb_tl
      \int_set:Nn\l_tmpa_int{\tl_use:N\l_tmpb_tl}
    }
    \prg_replicate:nn{\l_tmpa_int}{\tl_use:N\l_tmpa_tl}
  }
}
\end{MacroCode}
  \end{macro*}
  \begin{macro*}{\__skmath_pd_fraction:nn}[2]
    {Tokens representing a mathematical function}
    {Comma-separated list of variables, possibly with superscripts}
\begin{MacroCode}{package}
\cs_new_nopar:Npn\__skmath_pd_fraction:nn#1#2{
  \frac{
    \partial
    \__skmath_pd_if_vars_sum_above_one:nT{#2}{
      \c_math_superscript_token{\__skmath_pd_vars_sum:n{#2}}
    }
    {#1}
  }{
    \__skmath_pd_superscript_vars:n{#2}
  }
}
\end{MacroCode}
  \end{macro*}
  \begin{macro*}{\__skmath_pd_subscript:nn}[2]
    {Tokens representing a mathematical function}
    {Comma-separated list of variables, possibly with superscripts}
\begin{MacroCode}{package}
\cs_new_nopar:Npn\__skmath_pd_subscript:nn#1#2{
  {#1}\c_math_subscript_token{
    \__skmath_pd_subscript_vars:n{#2}
  }
}
\end{MacroCode}
  \end{macro*}
  \begin{macro*}{\__skmath_td_fraction:nn}[2]
    {Tokens representing a mathematical function}
    {A single variable, possibly with a superscript}
\begin{MacroCode}{package}
\cs_new_nopar:Npn\__skmath_td_fraction:nn#1#2{
  \frac{
    \__skmath_total_derivative_d:
    \__skmath_pd_if_vars_sum_above_one:nT{#2}{
      \c_math_superscript_token{\__skmath_pd_vars_sum:n{#2}}
    }
    {#1}
  }{
    \__skmath_total_derivative_d:
    #2
  }
}
\end{MacroCode}
  \end{macro*}

  Definition of \cs{bar}, \cs{pd}, \cs{td} and \cs{d} is deferred until after all
  packages are loaded to avoid collisions with other packages.
\begin{MacroCode}{package}
\AtBeginDocument{%
\end{MacroCode}
  The \cs{bar} command is modified to impove typesetting.
  \begin{macro}{\bar}
  \changes{0.1b}{Added \cs{bar} replacement}
  \changes{0.1h}{Wrap in \cs{AtBeginDocument}}
\begin{MacroCode}{package}
\DeclareDocumentCommand\bar{m}{%
    \ensuremath{\mkern 1.5mu\overline{\mkern-1.5mu{#1}\mkern-1.5mu}\mkern 1.5mu}}
\end{MacroCode}
  \end{macro}

  This is the partial derivative macro, but most of the functionality
  was defined as private macros earlier.
  \begin{macro}{\pd}[3]
    {Boolean distinguishing between starred and unstarred variant}
    {Tokens representing a mathematical function}
    {Comma-separated list of variables, possibly with superscripts}
\begin{MacroCode}{package}
\DeclareDocumentCommand\pd{smm}{
  \ensuremath{
    \IfBooleanTF{#1}
      {\__skmath_pd_subscript:nn{#2}{#3}}
      {\__skmath_pd_fraction:nn{#2}{#3}}
  }
}
\end{MacroCode}
  \end{macro}

  We also have the total derivative macro,
  \begin{macro}{\td}[2]
    {Tokens representing a mathematical function}
    {A single variable, possibly with a superscript}
\begin{MacroCode}{package}
\DeclareDocumentCommand\td{mm}{
  \ensuremath{
    \__skmath_td_fraction:nn{#1}{#2}
  }
}
\end{MacroCode}
  \end{macro}

  We introduce a command to typeset the differential part
  of integrals, shamefully stolen from an answer on \TeX.SE.
  \begin{macro}{\d}
  \changes{0.1a}{Fixed obtuse errors}
  \changes{0.1b}{Moved to \textsf{xparse} command definition}
  \changes{0.2}{Use \cs{peek_meaning_ignore_spaces:NT} instead of \cs{@ifnextchar}}
  \changes{0.3b}{Use \cs{operator@font} instead of \cs{mathrm}}
\begin{MacroCode}{package}
\DeclareDocumentCommand\d{m}{\ensuremath{\,\__skmath_integral_d: #1%
                              \peek_meaning_ignore_spaces:NT\d{\!}}}
\end{MacroCode}
  \end{macro}
\begin{MacroCode}{package}
}
\end{MacroCode}

  Finally, we define a nicer way to denote vectors.
  \begin{macro}{\vec}
  \changes{0.2}{Use \cs{cs_new_eq:NN} instead of \cs{let}}
\begin{MacroCode}{package}
\cs_set_eq:NN\vec\vectorsym
\end{MacroCode}
  \end{macro}

\begin{MacroCode}{package}
\endinput
\end{MacroCode}

    \Finale
    \section{Installation}
    The easiest way to install this package is using the package
    manager provided by your \LaTeX\ installation if such a program
    is available. Failing that, provided you have obtained the package
    source (\file{skmath.tex} and \file{Makefile}) from either CTAN
    or Github, running \texttt{make install} inside the source directory
    works well. This will extract the documentation and code from
    \file{skmath.tex}, install all files into the TDS tree at
    \texttt{TEXMFHOME} and run \texttt{mktexlsr}.

    If you want to extract code and documentation without installing
    the package, run \texttt{make all} instead. If you insist on not
    using \texttt{make}, remember that packages distributed using
    \pkg{skdoc} must be extracted using \texttt{pdflatex}, \emph{not}
    \texttt{tex} or \texttt{latex}.

    \PrintChanges
    \PrintIndex
\end{document}


\documentclass[12pt]{article}

\include{preamble}

\title{Math 621 Fall 2017 \\ Midterm Examination One}
\author{Professor Adam Kapelner}

\date{October 3, 2017}

\begin{document}
\maketitle

\noindent Full Name \line(1,0){410}

\thispagestyle{empty}

\section*{Code of Academic Integrity}

\footnotesize
Since the college is an academic community, its fundamental purpose is the pursuit of knowledge. Essential to the success of this educational mission is a commitment to the principles of academic integrity. Every member of the college community is responsible for upholding the highest standards of honesty at all times. Students, as members of the community, are also responsible for adhering to the principles and spirit of the following Code of Academic Integrity.

Activities that have the effect or intention of interfering with education, pursuit of knowledge, or fair evaluation of a student's performance are prohibited. Examples of such activities include but are not limited to the following definitions:

\paragraph{Cheating} Using or attempting to use unauthorized assistance, material, or study aids in examinations or other academic work or preventing, or attempting to prevent, another from using authorized assistance, material, or study aids. Example: using an unauthorized cheat sheet in a quiz or exam, altering a graded exam and resubmitting it for a better grade, etc.
\\

\noindent I acknowledge and agree to uphold this Code of Academic Integrity. \\

\begin{center}
\line(1,0){250} ~~~ \line(1,0){100}\\
~~~~~~~~~~~~~~~~~~~~~signature~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ date
\end{center}

\normalsize

\section*{Instructions}

This exam is seventy five minutes and closed-book. You are allowed one page (front and back) of a \qu{cheat sheet.} You may use a graphing calculator of your choice. Please read the questions carefully. If the question reads \qu{compute,} this means the solution will be a number otherwise you can leave the answer in choose, permutation, exponent, factorial or any other notation which could be resolved to a number with a computer. I advise you to skip problems marked \qu{[Extra Credit]} until you have finished the other questions on the exam, then loop back and plug in all the holes. I also advise you to use pencil. The exam is 100 points total plus extra credit. Partial credit will be granted for incomplete answers on most of the questions. \fbox{Box} in your final answers. Good luck!

\pagebreak

\problem Below are some theoretical exercises.

\benum
\subquestionwithpoints{7}  Assume independent r.v.'s $X$ and $Y$ where $\support{X} = (0, \infty)$ and $\support{Y} = (0, \infty)$. Beginning from the general definition of convolution, prove that

\beqn
f_{X + Y}(t) =  \int\displaylimits_0^t f_X(x) f_Y(t-x) dx
\eeqn

where by convention, the notation $f_X$ represents the PDF of r.v. $X$ which \emph{does not include} an indicator function.
 \spc{8}

\subquestionwithpoints{7}  If $X,Y \iid \exponential{\lambda}$, find $\prob{X \geq Y}$. \spc{10}

\subquestionwithpoints{10}  If $X,Y \iid \exponential{\lambda}$, find the conditional density of $X$ given $X+Y$. There is no guarantee that the result will be the density of a brand name r.v., but if it is, denote it and find the parameter(s) as a function of $\lambda$. \spc{10}

\subquestionwithpoints{7}  Let $X \sim \binomial{n_1}{p_1}$ independent of $Y \sim \binomial{n_2}{p_2}$. Find the PMF of $X+Y$ \textit{as best as you possibly can} (even if there is no closed form solution). \spc{10}

\subquestionwithpoints{7}  Let $X \sim \binomial{2000}{0.004}$ independent of $Y \sim \binomial{20000}{0.0004}$. Approximate $\prob{X + Y = 0}$. The correct answer uses one simple operation and no credit will be given for answers that require the use of non-trivial computing. \spc{10}

\subquestionwithpoints{5}  Let $X \sim \negbin{35}{0.37}$ independent of $Y \sim \geometric{0.37}$. Find the PMF of $X + Y$. \spc{10}

\subquestionwithpoints{5} Calculate $\gamma(5,24.5) + \displaystyle\int\displaylimits_{24.5}^\infty t^4 e^{-t}dt$ as a number $\in \naturals$ explicitly. \spc{10}

\eenum

\problem Below are some questions about waiting times.

\benum

\subquestionwithpoints{5} The time until phone the next phone call is exponentially distributed with an average of half hour. If you have already waited half hour, find the probability you will wait more than another half hour. \spc{10}

\subquestionwithpoints{5} The time until phone the next phone call is exponentially distributed with an average of half hour. What is the probability you get two phone calls in one hour? \spc{10}

\subquestionwithpoints{7} The time until phone the next phone call is exponentially distributed with an average of half hour. What is the probability you get 10 phone calls before 5hr? You can answer using the CDF of a r.v. you define.\spc{10}

\eenum

\problem Below are some theoretical exercises about the vector-valued r.v.'s.

\benum
\subquestionwithpoints{6} Let $\Xoneton \iid \binomial{n}{p}$ and let $\X$ denote the vector of these r.v.'s. Find $\var{\X}$. \spc{10}

\subquestionwithpoints{7} Let $\Xoneton \iid \binomial{n_0}{p}$ and let $\X$ denote the vector of these r.v.'s. Is $\X \sim \multinomial{m}{\p}$? If yes, find the values of its parameters, $m$ and $\p$ as functions of $n_0$ and $p$. If no, explain why not. \spc{10}

\subquestionwithpoints{7} A person goes to the grocery store and buys $n$ fruits. For each of his $n$ selections, he picks rambutans with probability $p$ otherwise he picks dragonfruits. If rambutans cost $a$ and dragonfruits cost $b$, find his expected bill. \spc{4}

\subquestionwithpoints{15} Find the standard deviation of his bill and simplify as best as possible.\spc{10}
\eenum

\end{document}


\documentclass{article}

%%%%%% Include Packages %%%%%%
\usepackage{sectsty}
\usepackage{amsmath,amsfonts,amsthm,amssymb}
\usepackage{fancyhdr}
\usepackage{lastpage}
\usepackage{setspace}
\usepackage{graphicx}
\usepackage{array}

%%%%%% Formatting Modifications %%%%%%

\usepackage[margin=2.5cm]{geometry} %% Set margins
\sectionfont{\sectionrule{0pt}{0pt}{-8pt}{0.8pt}} %% Underscore section headers
\setstretch{1.2} %% Set 1.2 spacing

%%%%%% Set Homework Variables %%%%%%

\newcommand{\hwkNum}{10}
\newcommand{\hwkAuthors}{Ben Drucker}

%%%%%% Set Header/Footer %%%%%%

\pagestyle{fancy}
\lhead{\hwkAuthors}
\rhead{Homework \#\hwkNum}
\rfoot{\textit{\footnotesize{\thepage /\pageref{LastPage}}}}
\cfoot{}
\renewcommand\headrulewidth{0.4pt}
\renewcommand\footrulewidth{0.4pt}

%%%%%% Document %%%%%%

\begin{document}

\title{Homework \#\hwkNum}
\author{\hwkAuthors}
\date{}

\maketitle

%%%%%% Begin Content %%%%%%

\section*{6.2}
	\subsection*{8}
		\subsubsection*{a)}
			$P \left [ z_{\alpha_1} \leq (\overline{X} - \mu) \frac{\sigma}{\sqrt{n}} \leq z_{\alpha_2} \right ] = 1-\alpha.$ Solving for $\mu: \overline{X} - z_{\alpha_2}  \frac{\sigma}{\sqrt{n}} \leq \mu \leq \overline{X} + z_{\alpha_1} \frac{\sigma}{\sqrt{n}}.\\
			\left ( \overline{X} - z_{\alpha_2} \frac{\sigma}{\sqrt{n}} ,  \overline{X} + z_{\alpha_1}  \frac{\sigma}{\sqrt{n}} \right )$
		\subsubsection*{b)}
			$z_{\alpha_1} = 2.24;
				z_{\alpha_2} = 1.78. $ So the width is: $(2.24+1.78) \frac{\sigma}{\sqrt{n}} = 4.02 \frac{\sigma}{\sqrt{n}}.$ This is wider than the $3.96\frac{\sigma}{\sqrt{n}}$ width of the 7.5 interval.
\section*{7.2}
	\subsection*{12}
		$.81 \pm 2.58 \frac{.34}{\sqrt{110}} = (.73, .89)$
	\subsection*{14}
		\subsubsection*{a)}
			$89.1 \pm 1.96 \frac{3.73}{\sqrt{169}} = (88.54, 89.66).$ This interval appears very precise.
		\subsubsection*{b)}
			$ n = \left ( \frac{1.96*.16}{.5} \right )^2 = 245.9; n = 246.$
	\subsection*{18}
		$\overline{x} - z_{1-.9} \frac{s}{\sqrt{n}} = 4.25 - 1.28 \frac{1.3}{\sqrt{75}} = 4.059$
	\subsection*{20}
		$.15 \pm 2.58 \sqrt{ \frac{.15*.85}{4722}} = (.137, .163)$
\section*{7.3}
	\subsection*{28}
	Via a $t$ table:
		\subsubsection*{a} 1.341
		\subsubsection*{b} 1.753
		\subsubsection*{c} 1.708
		\subsubsection*{d} 1.684
		\subsubsection*{e} 2.704
	\subsection*{30}
	Via a $t$ table:
		\subsubsection*{a} $t_{.025, 10} = 2.228$
		\subsubsection*{b} $t_{.025, 15} = 2.131$
		\subsubsection*{c} $t_{.005, 15} = 2.947$
		\subsubsection*{d} $t_{.005, 4} = 4.604$
		\subsubsection*{e} $t_{.01, 24} = 2.492$
		\subsubsection*{e} $t_{.005, 37} = 2.712$

%%%%%% End Content %%%%%%
\end{document}

Spring 2013/STAT W1211 - Statistics/Homework/Homework 10/Homework 10.tex


%% Slide
\subsection{Absorption Edge Energies}
\begin{frame} \frametitle{Absorption Edge Energies of the Elements}
  \small

  \begin{cenpage}{103mm}

    The energies of the {\slshape{K}} shell absorption edges for the
    elements go as  $E_K \sim Z^2$.

    {\wgraph{85mm}{general/kl_edges}}

    Elements with $Z > 18$ have {\slshape{K}}-, or {\slshape{L}}-edge
    between 2 and 35 keV, which can be accessed at many synchrotron
    sources.

    \vmm
    Lower $Z$ elements (softer x-rays) can be measured as well, but may
    require working in vacuum.
  \end{cenpage}

\vfill
\end{frame}


\input{templates/lec_template.tex}

\begin{document}

\title[Strings]{Week 5: Strings}
\subtitle{Basic Programming in Python}

\author[kgross, mpoemsl, sselbach]{Katharina Groß, Martin Pömsl, Sören Selbach}

% change to date of actual lecture
\date{\today}

\begin{frame}[plain]
    \titlepage
\end{frame}

\begin{frame}
    \tableofcontents
\end{frame}

\section{Recap: Lists}

\begin{frame}[plain]
    \sectionpage
\end{frame}

\begin{frame}[fragile]{List Slicing}

    \textbf{Task: Print only the last three elements of a list}

    \begin{pythoncode}

my_list = [1, 2, 3, 4, 5]
print(my_list[-3:])

# Output: [3, 4, 5]

    \end{pythoncode}

    \note{
        This is called \texttt{slicing}.
    }

\end{frame}

\begin{frame}[fragile]{List Comprehension}

    \textbf{Task: Solve the Wheat and Chessboard Problem}

    \begin{pythoncode}

result = sum([2 ** n for n in range(64)])

print([2 ** n for n in range(64)])
# Output: [1, 2, 4, 8, 16, ...]

print([n for n in range(64)])
# Output: [0, 1, 2, 3, 4, ...]

print([2 for n in range(64)]
# Output: [2, 2, 2, 2, 2, ...]
    \end{pythoncode}

    \note{
        Everything that can be done with List Comprehension can also be done with a \texttt{for}-loop, so don't worry if you don't understand it right away.
    }

\end{frame}

\begin{frame}[fragile]{List Comprehension}

    \textbf{Task: Filter a list for odd or even numbers}

    \begin{pythoncode}

original_list = [1, 7, 8, 2, 3]

odd_only = [n for n in original_list if n % 2 != 0]

print(odd_only)
# Output: [1, 7, 3]

even_only = [n for n in original_list if n % 2 == 0]

print(even_only)
# Output: [8, 2]

    \end{pythoncode}

    \note{
        It is also possible to include an \texttt{else} instruction.
    }

\end{frame}

\begin{frame}[fragile]{Strings as Lists of Characters}

    \begin{pythoncode}

my_string = "banana"

print(len(my_string))
# Output: 6

print(my_string[-3:])
# Output: ana

print(sorted(my_string))
# Output: ['a', 'a', 'a', 'b', 'n', 'n']

print([c for c in my_string if c != 'a'])
# Output: ['b', 'n', 'n']

    \end{pythoncode}

    \note{
        Note that the return value of \texttt{sorted(my\_string)} is a list, not a string.
    }

\end{frame}

\begin{frame}[fragile]{Strings as Lists of Characters}

    \begin{pythoncode}

my_string = "banana"

for character in my_string:
    print(character)

# Output:
# b
# a
# n
# a
# n
# a

    \end{pythoncode}

    \note{
        The variable "character" will be assigned the value of the current character
        in each iteration of the \texttt{for}-loop.
    }

\end{frame}

\begin{frame}[fragile]{Unicode Table}

	\includegraphics[width=0.9\textwidth]{05_Strings/unicode_table.png}

    \note{
        You can find the full unicode table here:

        \vspace{1em}

        \url{http://www.tamasoft.co.jp/en/general-info/unicode-decimal.html}
    }

\end{frame}

\begin{frame}[fragile]{Calculating with Characters}

    \textbf{The unicode table assigns a unique decimal number to each character.}

    \vspace{1em}

    We can use \texttt{ord} to get the corresponding \texttt{int} of a character and \texttt{chr} to get the corresponding character of an \texttt{int} in Python.

    \vspace{1em}

    \centering \includegraphics[width=0.5\textwidth]{05_Strings/unicode_table.png}

    \note{
        You can find the full unicode table here:

        \vspace{1em}

        \url{http://www.tamasoft.co.jp/en/general-info/unicode-decimal.html}
    }

\end{frame}

\begin{frame}[fragile]{Calculating with Characters}

    \begin{pythoncode}

print(ord('a'))
# Output: 97

print(chr(97))
# Output: a

print('a' + 1)
# TypeError: can only concatenate str (not "int") to str

print(chr(ord('a') + 1))
#     chr(97       + 1)
#     chr(98)
# Output: b

    \end{pythoncode}

    \note{

        Hint: This is particularily relevant for the Caesar Cipher task.

        \vspace{1em}

        When working with letters, one must make sure not to "drop off" one end of the Latin letters.

        \vspace{1em}

        For example, if you try to increase the letter "z" by 1 with this method, you will
        instead end up at "\{" since this is the next cell in the unicode table.

        \vspace{1em}

        So you have to find a way to make sure that when the result of \texttt{ord(my\_letter) + 1} is greater than 122,
        it will start counting at 97 again.

    }

\end{frame}

\section{Creating Strings}

\begin{frame}[plain]
    \sectionpage
\end{frame}

\begin{frame}[fragile]{Creating Strings}

    \begin{enumerate}
        \item Explicitly, e.g. \texttt{my\_string\_1 = "banana"}
        \item Casting, e.g. \texttt{my\_string\_2 = str(97)}
        \item Creating a character, e.g. \texttt{my\_string\_3 = chr(97)}
        \item Special String functions, \newline e.g. \texttt{my\_string\_4 = 'a'.join(['b', 'n', 'n'])}
    \end{enumerate}

    \begin{pythoncode}
# Output of print(my_string_1): banana
# Output of print(my_string_2): 97
# Output of print(my_string_3): a
# Output of print(my_string_4): banan
    \end{pythoncode}

    \note{
        The most common way is to explicitly define them. \texttt{join} will also be explained later on.
    }

\end{frame}

\section{Formatting Strings}

\begin{frame}[plain]
    \sectionpage
\end{frame}

\begin{frame}[fragile]{\texttt{format}}

    \texttt{format} can be used to insert values into a string without the usage of string concatenation with +.

    \begin{pythoncode}
n = 1
my_string = "Hello! This is example number {}.".format(n)

print(my_string)
# Output: Hello! This is example number 1.

print("After example {} comes example {}.".format(1, 2))
# Output: After example 1 comes example 2.

    \end{pythoncode}

    \note{
        For more information about \texttt{format} syntax, see:

        \vspace{1em}

        \url{https://docs.python.org/3.7/library/string.html\# format-string-syntax}
    }

\end{frame}

\begin{frame}[fragile]{\texttt{format}}

    It is also possible to index the arguments of \texttt{format} and use them multiple times.

    \begin{pythoncode}

print("I am {1}, so I {0}.".format("eat", "hungry"))
# Output: I am hungry, so I eat.

print("{0} + {0} = {1}".format(1, 2))
# Output: 1 + 1 = 2

print("{season_1} goes, {season_2} comes".format(
    season_1="winter",
    season_2="spring"
))
# Output: winter goes, spring comes

    \end{pythoncode}

    \note{

        The indexing follows the same system as with lists:

        \vspace{1em}

        The first element is at index 0, the second at index 1, ...
    }

\end{frame}

\begin{frame}[fragile]{\texttt{format}}

    There is even a whole mini language surrounding the use of \texttt{format}. For our purposes, however, it is enough to know how to use fixed-point notation.

    \begin{pythoncode}
result = 2 ** 0.5 # square root of 2

print("The result is {0}.".format(result)
# Output: The result is 1.4142135623730951.

print("The result is {0:.4f}.".format(result)
# Output: The result is 1.4142.

print("The result is {0:.2f}.".format(result)
# Output: The result is 1.41.
    \end{pythoncode}

    \note{
        For more information about \texttt{format} syntax, see:

        \vspace{1em}

        \url{https://docs.python.org/3.7/library/string.html\# format-string-syntax}
    }

\end{frame}

\section{Handling Whitespace}

\begin{frame}[plain]
    \sectionpage
\end{frame}

\begin{frame}[fragile]{Whitespace Characters}

    \begin{enumerate}

    \item \texttt{\textbackslash n} inserts a linebreak
    \item \texttt{\textbackslash t} inserts a tab
    \item The length of a tab is system dependent (2, 4 or 8 spaces)
    \item A regular space " " is of course also a whitespace character
    \item \texttt{isspace()} can be used to check if a character is a whitespace

    \end{enumerate}

    \begin{pythoncode}

my_string = "a\nb\tc"

print(my_string)
# Output:
# a
# b    c

    \end{pythoncode}

    \note{
        There are a lot more whitespace characters, but those are the most relevant ones for our purposes.
    }

\end{frame}

\begin{frame}[fragile]{Whitespace Characters}

    \begin{pythoncode}

my_string = "a \nb\tc"

for character in my_string:
    print(character.isspace())

# Output:
# False
# True
# True
# False
# True
# False

    \end{pythoncode}

    \note{
        \texttt{isspace} checks for all whitespace characters (not only the ones we know).
    }

\end{frame}

\begin{frame}[fragile]{Removing Whitespace}

    \textbf{There are three main functions to remove whitespace:}

    \begin{enumerate}

    \item \texttt{strip} removes all whitespace characters to the left and right of a string
    \item \texttt{split} divides a string on all whitespace characters and returns a list of the parts
    \item \texttt{splitlines} divides a string on all linebreaks and returns a list of lines

    \end{enumerate}

    \note{

        \texttt{split} and \texttt{join} in combination can be really useful.

    }

\end{frame}

\begin{frame}[fragile]{Removing Whitespace}

    \begin{pythoncode}

my_string = "\tEnjoy the \n sun !  ! !\n"

print(my_string)
# Output:
#	 Enjoy the
# sun !  ! !
#

print(my_string.strip())
# Output:
# Enjoy the
#  sun !  ! !

    \end{pythoncode}

\end{frame}

\begin{frame}[fragile]{Removing Whitespace}

    \begin{pythoncode}
my_string = "\tEnjoy the \n sun !  ! !\n"

print(my_string.split())
# Output: ['Enjoy', 'the', 'sun', '!', '!', '!']

print(my_string.splitlines())
# Output: ['\tEnjoy the ', ' sun !  ! !']

# We can merge the resulting lists together with join

print(" ".join(my_string.split()))
# Output: Enjoy the sun ! ! !

    \end{pythoncode}

\end{frame}

\begin{frame}[fragile]{Excursion: Whitespace in Python}

    \centering \includegraphics[width=0.75\textwidth]{05_Strings/tabs_vs_spaces.jpg}

    \note{
        The picture is taken from an episode of the series Silicon Valley, which depicts the struggle of programmers in California in a funny way.

        \vspace{1em}

        The referred scene about the whole "Tabs vs. Spaces" argument can also be found on YouTube.

    }

\end{frame}

\begin{frame}[fragile]{Excursion: Whitespace in Python}

    In Python, we use whitespace to \textbf{indent blocks of code}.
    These can either be produced using tabs or spaces.
    If you mix them in your Python code, you will get an \texttt{IndentationError}.

    \begin{pythoncode}

if my_condition:
    print(my_old_variable)
    my_new_variable = my_old_variable + 1
    print(my_new_variable)

print(my_condition)

    \end{pythoncode}

    \textbf{In this course, we ask you to use four spaces just so we can all edit and execute each other's code.}

    \note{

        Having the same convention about tabs and spaces is particularily important when collaborating on a project with other programmers.

    }

\end{frame}

\section{Evaluating Strings}

\begin{frame}[plain]
    \sectionpage
\end{frame}

\begin{frame}[fragile]{Checking Strings}

    There are many functions that check whether a string fulfills a certain condition. They return a boolean value (\texttt{True} or \texttt{False}).

    \vspace{1em}

    They all follow this basic syntax:

    \begin{pythoncode}

my_string_1 = "hello people"
my_string_2 = "Hello people"
my_string_3 = "HELLO PEOPLE"

boolean_value = my_string_1.islower()

print(boolean_value)
# Output: True

    \end{pythoncode}

    \note{
        What is being checked is whether \textbf{all} characters in the string fulfill the condition.

        \begin{enumerate}

        \item \texttt{isalpha} checks if a string is all alphabetic
        \item \texttt{isnumeric} checks if a string is all numeric
        \item \texttt{isalnum} checks if a string is all alphabetic or numeric
        \item \texttt{isupper} checks if a string is all lowercase
        \item \texttt{islower} checks if a string is all uppercase
        \item \texttt{isspace} checks if a string is all whitspace
        \item \texttt{startswith} checks if a string starts with another string
        \item \texttt{endswith} checks if a string ends with another string

        \end{enumerate}
    }

\end{frame}

\begin{frame}[fragile]{Checking Strings}

    \begin{pythoncode}

my_string_1 = "hello people"
my_string_2 = "Hello people"
my_string_3 = "HELLO PEOPLE"

print(my_string_1.islower())
# Output: True

print(my_string_3.islower())
# Output: False

print(my_string_2.islower())
# Output: ???

    \end{pythoncode}

    \note{

        What is being checked is whether \textbf{all} characters in the string fulfill the condition.

        \begin{enumerate}

        \item \texttt{isalpha} checks if a string is all alphabetic
        \item \texttt{isnumeric} checks if a string is all numeric
        \item \texttt{isalnum} checks if a string is all alphanumeric
        \item \texttt{isupper} checks if a string is all lowercase
        \item \texttt{islower} checks if a string is all uppercase
        \item \texttt{isspace} checks if a string is all whitspace
        \item \texttt{startswith} checks if a string starts with another string
        \item \texttt{endswith} checks if a string ends with another string

        \end{enumerate}
    }

\end{frame}

\begin{frame}[fragile]{Evaluating Strings}

    \begin{enumerate}

        \item \texttt{len} can be used to obtain the total number of characters in a string
        \item \texttt{in} can be used to check if a string is contained in another string
        \item \texttt{count} can be used to obtain the number of occurences of a string in another string
        \item \texttt{find} can be used to obtain the index of the first occurence of a string in another string

    \end{enumerate}

    \note{

        All of these functions return an \texttt{int}.

        \vspace{1em}

        You can find the indices of multiple occurrences by applying \texttt{find} multiple times,
        specifying the start index and increasing in after each found index.

        \vspace{1em}

        More information on \texttt{find} can be found here:

        \vspace{1em}

        \url{https://docs.python.org/3/library/stdtypes.html\# str.find}

    }

\end{frame}

\begin{frame}[fragile]{Evaluating Strings}

    \begin{pythoncode}

my_string = "the quick brown fox jumps over the lazy dog"

print(len(my_string))
# Output: 43

print("fox" in my_string)
# Output: True

print("banana" in my_string)
# Output: False

    \end{pythoncode}

    \note{
        \texttt{in} can also be used on lists.
    }

\end{frame}

\begin{frame}[fragile]{Evaluating Strings}

    \begin{pythoncode}

my_string = "the quick brown fox jumps over the lazy dog"

print(my_string.count("fox"))
# Output: 1

print(my_string.count("the"))
# Output: 2

print(my_string.find("the"))
# Output: 0

    \end{pythoncode}

     \note{
        \texttt{count} can also be used on lists.
    }

\end{frame}

\section{Modifying Strings}

\begin{frame}[plain]
    \sectionpage
\end{frame}

\begin{frame}[fragile]{Immutability}

    \textbf{Strings are immutable}, so despite their similarities with lists they cannot be changed.

    \begin{pythoncode}

my_string = "banana"

print(my_string[2])
# Output: n

my_string[2] = 'i'
# TypeError: 'str' object does not support item assignment

    \end{pythoncode}

    \note{
         Like \texttt{tuples}, strings can be indexed, but not changed. So all functions that appear to change a string in fact just return a changed copy.
    }

\end{frame}

\begin{frame}[fragile]{Changing Case}

    These functions change the capitalization of the words in a string:

    \begin{enumerate}

        \item \texttt{upper} can be used to make all characters uppercase
        \item \texttt{lower} can be used to make all character lowercase
        \item \texttt{title} can be used to make all words title case

    \end{enumerate}

    \begin{pythoncode}

my_string = "hello, How are YOU?"

my_string_lower = my_string.lower()
my_string_upper = my_string.upper()

print(my_string, my_string_lower, "\n", my_string_upper)
# Output: hello, How are YOU? hello, how are you?
#          HELLO, HOW ARE YOU?

    \end{pythoncode}

    \note{

        For properties like cases there always exists a pair of functions such that:

        \vspace{1em}

        \texttt{my\_string.property()} transforms the string to have this property.

        \vspace{1em}

        \texttt{my\_string.isproperty()} returns a boolean whether as the string has this property.

    }

\end{frame}

\begin{frame}[fragile]{\texttt{strip}}

    \texttt{strip} can also take an argument and remove an arbitrary string from both sides of a string:

    \begin{pythoncode}

my_string = "banana HELLO banana"

print(my_string.strip("banana"))
# Output: HELLO

    \end{pythoncode}

    There exist functions \texttt{rstrip} and \texttt{lstrip} as well to apply this to only one side of the string.

    \note{
        \texttt{rstrip} strips from the right side, \texttt{lstrip} from the left side.
    }

\end{frame}

\begin{frame}[fragile]{\texttt{split} and \texttt{join}}

    \texttt{split} can split on a custom string as well:

    \begin{pythoncode}

my_string = "banana HELLO banana"

print(my_string.split(" HELLO "))
# Output: ['banana', 'banana']

    \end{pythoncode}

    Using this in combination with \texttt{join}, it is possible to replace all occurences of a string with another string.

    \vspace{1em}

    However, for this there also exists a specialized function \texttt{replace}.

\end{frame}

\begin{frame}[fragile]{\texttt{split} and \texttt{join}}

    \textbf{Task: Replace all occurences of "Tom" with another name.}

    \begin{pythoncode}

my_string = """One day there was a baker named Tom.
Tom liked to bake a lot of breads. """

my_string_splitted = my_string.split("Tom")
print(my_string_splitted)
# Output: ['One day there was a baker named ',
# '. \n', ' liked to bake a lot of breads. ']

my_string_joined = "Mary".join(my_string_splitted)
print(my_string_joined)
# Output: One day there was a baker named Mary.
# Mary liked to bake a lot of breads.

    \end{pythoncode}

    \note{
        The triple quotation mark """ can be used to start and end multiline strings. Multiline strings are strings that span more than one line of text.
    }

\end{frame}

\begin{frame}[fragile]{\texttt{replace}}

    \textbf{Task: Replace all occurences of "Tom" with another name."}

    \begin{pythoncode}

my_string = """One day there was a baker named Tom.
Tom liked to bake a lot of breads. """

my_string_replaced = my_string.replace("Tom", "Mary")

print(my_string_replaced)
# Output: One day there was a baker named Mary.
# Mary liked to bake a lot of breads.

    \end{pythoncode}

\end{frame}

\section{Outlook: RegEx}

\begin{frame}[plain]
    \sectionpage
\end{frame}

\begin{frame}[fragile]{Outlook: RegEx}

    \textbf{Regular Expressions} are a powerful tool to replace not just predefined strings, but any string that matches a pattern.

    \begin{pythoncode}

import re

re_example = re.compile("[0-9]")

my_string = "Guido van Rossum (born 31 January 1956) ..."

print(re_example.sub("X", my_string))
# Output: Guido van Rossum (born XX January XXXX) ...

    \end{pythoncode}

    \note{
        Learn more about RegEx here:

        \vspace{1em}

        \url{https://docs.python.org/3/howto/regex.html}
    }

\end{frame}

\begin{frame}[fragile]{Outlook: RegEx}

    \begin{pythoncode}

re_example_1 = re.compile("[a-z]")
re_example_2 = re.compile("[a-b]")
re_example_3 = re.compile("van|born")

print(re_example_1.sub("X", my_string))
# Output: GXXXX XXX RXXXXX (XXXX 31 JXXXXXX 1956) ...

print(re_example_2.sub("X", my_string))
# Output: Guido vXn Rossum (Xorn 31 JXnuXry 1956) ...

print(re_example_3.sub("X", my_string))
# Output: Guido X Rossum (X 31 January 1956) ...

    \end{pythoncode}

    \note{
        Learn more about RegEx here:

        \vspace{1em}

        \url{https://docs.python.org/3/howto/regex.html}

        \vspace{1em}

        Especially if you are interested in working with text data, RegEx is an invaluable and powerful tool.

        \vspace{1em}

        The whole syntax is much more sophisticated than what is covered on these slides.
    }

\end{frame}

\end{document}