Variables and Assignment

What will the following code output?

x=2;
y=x;
{x,y}

What will the following code output?

z:=x;
x=5;
{x,y,z}

Numbers

What is the difference between the following two statements?

4/3
4./3

You can also use the N function (“numerical approximation”) to get a decimal output:

N[4/17]

N[4/17,40]

N[4./17,100]

Repetition

We often want to do repetitive things in Mathematica. One construction is the Do loop.

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

If we want to make a list, the Table function may be more useful than the Do loop. Here is an example:

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

squares

squares+1

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 within each iteration of the loop, and then do something with the result. A variable used this way is called an accumulator. Here is an example: compute 1+2+3+4+..+10

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

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

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

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

N[sum]

course web site : math242.mlwright.org