Math 242 Day 1 Demonstration

Variables

Let's assign some variables. What is the result of the following?

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

What happens if I do the following?

z:=x (* delayed assignment *)
x=5;
{x,y,z}

Number Types

What is the difference between the following?

4/3
4./3

N[5/17]

N[5/17,100]

N[5./17,100]

5./17

Repetition

A lot of times we need to repeat things in Mathematica. One useful construct is the Do loop.

Do[Print[i],{i,1,10}]

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

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

Accumulators

Sometimes we need to write a loop that modifies a variable at each iteration.

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

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

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

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/(2i-1);
Print[{i,1/(2i-1),sum}],
{i,1,10}]
sum

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

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