MCM Day 1 Demonstration

Variables

What will be the output of the following code?

x=2;  (* immediate assignment *)
y=x;  (* immediate assignment *)
{x,y}

z:=x;  (* delayed assignment -- makes z track the value of x *)
x=5;
{x,y,z}

Number Types

What is the difference between the following two statements?

4/3
4.0/3

You can convert any number to a decimal using the N function:

N[5/17]

N[5/17,20]

N[1.2,20]

Repetition

We will often want to repeat things in our calculations. One useful construct is the Do loop.

Do[ Print[{i,i^2}], {i,5,20}]

If we want to make a list, Table is a useful function. Table really makes a list:

Table[i^2,{i,1,10}]

Accumulators

Often we need loops that modify some variable at each iteration. A common construct is to initialize a variable outside of a loop, update it with each iteration, and then do something with the result. A variable used this way is an accumulator.

Example: 1+2+3+4+5+...+10

sum=0;
Do[sum=sum+i;Print[sum],{i,1,10}]
sum

sum=0;
Do[sum=sum+i;Print[{i,sum}],{i,1,10}]
sum

sum=0;
Do[sum=sum+i,{i,1,200}]
sum

Exercise: compute 4(1-(1/3)+(1/5)-(1/7)+(1/9)-...)

sum=0
Do[sum=sum+1/i;Print[{i,sum}],{i,1,20,2}]

sum=0
Do[sum=sum+(-1)^(i+1)/(2*i-1);Print[{i,sum}],{i,1,20}]
sum

sum=0
Do[sum=sum+(-1)^(i+1)/(2*i-1),{i,1,2000}]
N[4*sum]