User Tools

Site Tools


gibson:teaching:fall-2014:math445:lecture10-diary

====== Differences ====== This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
gibson:teaching:fall-2014:math445:lecture10-diary [2014/10/15 13:04]
gibson
gibson:teaching:fall-2014:math445:lecture10-diary [2014/10/17 10:23] (current)
gibson
Line 1: Line 1:
 ====== Math 445 lecture 10: more ''​for''​ ====== ====== Math 445 lecture 10: more ''​for''​ ======
  
-Another illustration of the use of ''​for'' ​loops to compute a sum. Recall this classic formula for $\pi^2/6$ due to Euler:+The following example problem spells out in great detail how to translate a formula in summation notation into a Matlab ​''​for'' ​loop. 
 + 
 + 
 +Recall this classic formula for $\pi^2/6$ due to Euler: 
 +\begin{eqnarray*} 
 +\frac{\pi^2}{6} = \sum_{n=1}^{\infty} \frac{1}{n^2} = 1 + \frac{1}{2^2} + \frac{1}{3^2} + \frac{1}{4^2} + \frac{1}{5^2} +  \ldots  
 +\end{eqnarray*} 
 +We can sum the first N terms of this series with the Matlab one-liner 
 +<code matlab>​ 
 +N=100; sum((1:​N).^(-2)) 
 +</​code>​ 
 + 
 +We can also do the sum with a ''​for''​ loop. To see how to build the ''​for''​ loop, it's helpful to think of the series as a sequence of //partial sums// 
 +\begin{eqnarray*} 
 +P_1 = 1  
 +\end{eqnarray*}
 \begin{eqnarray*} \begin{eqnarray*}
-\frac{\pi^2}{6} ​= 1 + \frac{1}{2^2} ​+ \frac{1}{3^2} + \frac{1}{4^2} + \frac{1}{5^2} +  \ldots ​+P_2 = 1 + \frac{1}{2^2}
 \end{eqnarray*} \end{eqnarray*}
-Rewrite this with summation notation 
 \begin{eqnarray*} \begin{eqnarray*}
-\frac{\pi^2}{6} = \sum_{n=1}^{\infty} \frac{1}{n^2} +P_3 = 1 + \frac{1}{2^2\frac{1}{3^2} 
 \end{eqnarray*} \end{eqnarray*}
-The Nth partial sum $P_N$ of the infinite series ​is +etc. Note that the difference between successive partial sums is a single term.
 \begin{eqnarray*} \begin{eqnarray*}
-P_N \sum_{n=1}^{N} \frac{1}{n^2} ​+P_n P_{n-1} \frac{1}{n^2}
 \end{eqnarray*} \end{eqnarray*}
-Then $\pi^2/6 = \lim_{\rightarrow \infty} ​P_N$.+So we can compute the $N$th partial sum $P_N$ by successively adding the term $1/n^2$ for n going from 1 to N.
  
 +That's exactly we do when we compute the sum with a ''​for''​ loop. 
 +<code matlab>
 +N=100;
 +P=0;
 +for n=1:N
 +  P = P + 1/n^2;
 +end
 +</​code>​
 +At each step in the ''​for''​ loop, we compute $1/n^2$ for the current value of $n$, add it to the previously computed partial sum $P_{n-1}$, and then store the result into $P_n$. But, since we are only interested in the final value $P_N$, we just store the current value of the partial sum in the variable P and write over it with the next value each time we step through the loop. 
 + 
 +  ​
  
gibson/teaching/fall-2014/math445/lecture10-diary.1413403483.txt.gz · Last modified: 2014/10/15 13:04 by gibson