\documentclass[12pt,letterpaper]{article}

% ---- Standard packages only ----
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage{amsmath,amssymb,amsthm}
\usepackage{geometry}
\usepackage{graphicx}
\usepackage{fancyhdr}
\usepackage{enumitem}
\setlist[itemize]{itemsep=1pt,topsep=2pt,parsep=1pt,partopsep=0pt}
\usepackage{xcolor}
\usepackage{listings}
\usepackage[colorlinks=true,linkcolor=blue,citecolor=blue,urlcolor=blue]{hyperref}

% ---- Page layout ----
\geometry{margin=2.5cm,headheight=14pt,headsep=8pt}
\setlength{\parindent}{0pt}
\setlength{\parskip}{3pt plus 1pt}

% ---- Header / footer ----
\pagestyle{fancy}
\fancyhf{}
\rhead{\small\coursecode\ --- \studentname}
\lhead{\small Homework \hwnumber}
\rfoot{Page \thepage}
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\footrulewidth}{0.4pt}

% ---- Metadata (edit these) ----
\newcommand{\coursecode}{Phys 256}
\newcommand{\hwnumber}{2}
\newcommand{\studentname}{Student Name}

% ---- Python listings style ----
\definecolor{codebg}{rgb}{0.97,0.97,0.95}
\definecolor{codekey}{rgb}{0.20,0.40,0.70}
\definecolor{codecom}{rgb}{0.40,0.40,0.40}
\definecolor{codestr}{rgb}{0.60,0.10,0.10}

\lstdefinestyle{pythonstyle}{
  language=Python,
  backgroundcolor=\color{codebg},
  basicstyle=\ttfamily\small,
  keywordstyle=\color{codekey}\bfseries,
  commentstyle=\color{codecom}\itshape,
  stringstyle=\color{codestr},
  showstringspaces=false,
  breaklines=true,
  frame=single,
  rulecolor=\color{codecom},
  numbers=left,
  numberstyle=\tiny\color{codecom},
  stepnumber=1,
  numbersep=8pt,
  tabsize=4,
  captionpos=b
}
\lstset{style=pythonstyle}

% ---- \problem and \solution commands ----
\newcounter{problem}
\makeatletter
\newcommand{\problem}[1]{%
  \refstepcounter{problem}%
  \vspace{6pt}\noindent{\fontsize{14pt}{16pt}\bfseries Problem \theproblem: #1}%
  \par\nobreak\vspace{3pt}}
\newcommand{\solution}{%
  \vspace{-2pt}%
  {\fontsize{14pt}{16pt}\bfseries\noindent Solution\par\nobreak\vspace{2pt}}}
\makeatother

% ---- Custom compact title (redefines \maketitle) ----
\makeatletter
\renewcommand{\maketitle}{%
  \thispagestyle{empty}%
  \noindent{\Large\bfseries \coursecode\ --- Homework \hwnumber}%
  \par\vspace{2pt}%
  \noindent{\studentname}%
  \par\vspace{8pt}%
  \hrule\vspace{10pt}}
\makeatother

\begin{document}
\maketitle

% =========================================================
\section*{Instructions}
\begin{itemize}
  \item Submit written report in PDF format (with inlined code snippets, if it is
	  needed or required). Report must be submitted to Gradescope `hw02report'
	  assignment.
  \item Submit Python code to Gradescope `hw02code' assignment.
  \item When required, all relevant code for a given problem should be in
	  file named as \lstinline{pN.py} where `N' stands for problem
	  number, e.g. \lstinline{p1.py}, \lstinline{p2.py}, or
	  \lstinline{p10.py}. All code files should be contained in one `zip'
	  archive and uploaded for grading to Gradescope.
  \item The class web page will have templates with function definitions to which
	you must adhere!
  \item Do not forget to discuss test cases in your report.
\end{itemize}

\section*{Prerequisites}

Read help about \lstinline{plt.plot} from \lstinline{matplotlib} package,
\lstinline{np.linspace} and \lstinline{np.arange} from \lstinline{numpy}
package, and about the built-in \lstinline{print} command.

\problem{(2 points)}
%---------------------------------------------------------------
Plot the function $f(x)=\exp(-x^2/10)*\sin(x)$ for 400 linearly spaced points of $x$
in the region from $0$ to $2 \pi$. 
Points should be joined with solid lines.

Do not use any loops (for, while). Inline the code listing and  include the resulting figure in your report.

No additional code required for separate submission.

\problem{(2 points)}
%---------------------------------------------------------------
Plot the functions $x^2$ and $x^3/2+0.5$ for $100$ linearly spaced points of $x$
in the region from $-1$ to $+1$. 
$x^2$ should be a red solid line and the other function should be a black dashed line.

% Do not worry about black and white printouts as long as colors are present in pdf report file.

Do not use any loops (for, while). Include the resulting figure and inline code listing in the
body of your report.

No additional code required for separate submission.

\problem{(3 points)}
%---------------------------------------------------------------
Write a function that calculates the sum below
\begin{equation}
	S_N = \sum_{k=1}^N a_k
\end{equation}
for any integer $N<10^6$ where $a_k={1}/{k^{2k}}$ for odd $k$ and $a_k={1}/{k^{3k}}$ for even $k$. 
The function should return 0 if $N<1$.

Use a \lstinline{while} loop for the function implementation.
Is it better to start summing from high values $k=N$ downward toward $k=1$? Or is it better to do the conventional sum starting from $k=1$ and going upwards to $k=N$? Justify your answer. Implement the way which gives the most precise numerical answer.

Hint: you may find \lstinline{np.mod} function useful to check for even and odd
numbers.

\problem{(3 points)}
%---------------------------------------------------------------
Write a function that calculates
\begin{equation}
	1+\sum_{i=1}^N \frac{1}{x^i}
\end{equation}
for any integer $N < 10^6$ and floating-point number $x$.
The function should return 0 if $N<1$.
The function should return \lstinline{np.inf} if $x=0$.

\emph{Do not use loops} for this problem. Instead use \lstinline{np.array} and relevant operations with
it to obtain the final result. Use \lstinline{np.sum} for the final
summation. Note: unfortunately we have no control how summation is done by
the \lstinline{numpy} package, so we cannot do the same trick as above.

\problem{(5 points)}
%---------------------------------------------------------------
Code file submission is required for this part.

Write a function \lstinline{mycos(x, N)} that calculates the value of $\cos(x)$ at the
given point $x$ via the Taylor series up to $N$ terms. $x$ could be any
number from $-20 \pi$ to $20 \pi$.

Only the figure and inlined code is needed for the part below.

How well does  your code  handle  the  situation  with  large  $x$ values?
Take  $x=10\pi$ for  example.

Once you have your \lstinline{mycos(x, N)} function, make a plot of its error vs
the stock \lstinline{np.cos(x)} function for $x=\pi/4$ at different values of $N$ as
large as 10000. I.e. plot \lstinline{ np.abs ( mycos(x, N) - np.cos(x) ) }
for the relevant set of $N$. I {\bf strongly} suggest to use
\lstinline{plt.loglog} for this case. Does the error decrease as $N$ grows or is
there a strange saturation? Explain your observations.

How  far do  you need  to expand the Taylor  series to  get absolute
precision of $10^{-4}$? What value of $N$  do you find reasonable (no need to
state it beyond one significant digit). Why is this so?


\problem{(5 points)}
%---------------------------------------------------------------

Download  the data   file  ``hw02dataset.csv''  from  the   class  webpage.  It
represents the result  of someone's attempt  to find the resistance of a  sample via
measuring a voltage  drop ($V$) (1st  column) and
current ($I$) passing through the resistor at the
same  conditions (2nd  column). Judging  by the  number of  samples it  was an  automated
measurement.

\begin{itemize}
	\item Using Ohms law $R=V/I$ find the resistance ($R$) of this sample 
		(no need to print it out for each point at this step).
	\item Estimate the resistance of the sample (i.e. find the
		average resistance)  and  estimate the error bars of this estimate
		(i.e. find the standard deviation).
		Do not make the fitting with straight line (this is next
		week's material).
\end{itemize}

To perform these tasks you must write functions in your code submission to calculate the sample mean (\lstinline{mymean(x)})
and the sample standard deviation (\lstinline{mystd(x)}) that take $x$ as \lstinline{np.array}.

For post-processing and plotting it is sufficient to have inlined code listings included in your report.

As a reminder, the standard deviation is defined as
\begin{equation}
\sigma (x) = \sqrt{\frac{1}{N-1} \sum_{i=1}^N (x_i - \bar{x})^2}
\end{equation}
where $x$ is the set (vector) of data points, $\bar{x}$ is the average (mean),
and $N$ is the number of points in the set.

Additional requirements:

\begin{enumerate}
    \item {\bf Do not use} standard built-in \lstinline{np.mean} and \lstinline{np.std} functions
in your solution. You need to make your own code to calculate them. But feel free to 
test against \lstinline{python} \lstinline{numpy}  functions.
    \item Your implementation of  functions should be general i.e. they should be able to work with arrays of any
length bigger than one. I.e. do not make it specific to the provided data
file.
    \item If the standard deviation function receives an array with only
one data point it must return \lstinline{np.nan}. The \lstinline{len} function
is your friend to find the number of elements in the array.
\end{enumerate}

Note: read  help for \lstinline{np.std},  it has many  options, and you might
want to know about them. In particular, the default value of \lstinline{ddof} option is not what
you want it to be in order to check your work.

\end{document}
