First  Day  Mathematica  Demo

MATH  242 A, Spring 2024

Loops  in  Mathematica:

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

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

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

Loop  with  an  accumulator (a variable that adds up a total). Note the print statement to help you see what the loop is computing at each iteration:

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

Use the N function to convert  a fraction to a decimal:

N[5/7]

Mathematica Warm-Up Problems

Math 242: Modern Computational Mathematics (spring 2024)

Exercise 1: Use a loop with an accumulator to compute partial sums of 4(1-(1/3)+(1/5)-(1/7)+(1/9)-(1/11)+...). Experiment by computing sums with more and more terms, following the same pattern. What number results?

Here  is  one  solution. Note the included Print statement:

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

Here is the same solution with more readable formatting and without a Print statement. It adds up 10000 terms and converts the answer to a decimal:

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

Exercise 2: Use a loop with an accumulator to compute partial sums of (1+(1/2)+(1/3)+(1/4)+(1/5)+(1/6)+...). How many terms are required for the sum to exceed 3? How many terms to exceed 4? How many terms to exceed 5? What do you observe? What do you wonder?

Here  is  a  solution with a Print statement in the loop:

total=0;
Do[
Print[1/i];
total += 1/i,
{i,1,5}
]
total

Here  is  the  same  solution without the Print statement and with more terms.

total=0;
Do[
total += 1/i,
{i,1,100}
]
N[total]

By  trial-and-error, it takes 11 terms for the sum to exceed 3. It takes 31 terms for the sum to exceed 4, and it takes 83 terms for the sum to exceed 5.

total=0;
Do[
total += 1/i,
{i,1,83}
]
N[total]

Exercise 3: Use a loop with an accumulator to compute
1+(1/(2+(1/(2+(1/(2+(1/2))))))) 
Continue the pattern with more and more nested fractions. The result approaches what number?

This problem is tricky! For  this  problem it’s easist to work from the bottom up. Since the leftmost term is a 1 not a 2, we’ll handle it separately outside of the loop.

total=2;
Do[
Print["total: ",total];
total = 2+(1/total),
{i,1,5}
]
total = 1+(1/total)

Now run the solution for more terms without the Print statement:

total=2;
Do[
total = 2+(1/total),
{i,1,50}
]
total = 1+(1/total);
N[total,20]

Could this be (Sqrt[2])?

N[Sqrt[2],20]

Exercise 4: Use a loop with an accumulator to compute
3-(1/(4-(2/(5-(3/(6-(4/(7-...)))))))) 
Continue the pattern with more and more nested fractions. The result approaches what number?

Another  tricky problem! We will again work from the bottom up, but now our index will count down from a max value.

max=7;
total=max;
Do[
Print[{i,total}];
total=i-((i-2)/total),
{i,max-1,3,-1}
]
total

Check:

3-(1/(4-(2/(5-(3/(6-(4/7)))))))