A Little Help on Lab 8

Problem 2)

Please note that it is very important that you issue the command Clear[x] as part of your  Newton calculation!  If you don't, then Mathematica  will not understand that when you change the starting value x[0], that you want Mathematica  to recompute all the other values of x as well.

As a simple example of this, let's set up a Newton sequence that starts at x[0]=10:.

(* Newton's method for f(x)=0. *)
(* Just define f, and a starting value x[0] *)

Clear[f,n,x]

f[x_]:=Cos[x]-x

x[0] = 10;

x[n_] := x[n] = x[n-1] - f[x[n-1]] / f'[x[n-1]]//N

Now, if we ask for a table of the first five values, we get:

Table[ {n, x[n]}, {n,0,5}];
TableForm[%]

Now, if we want to change the starting point x[0], and do the Newton iteration again, we might just try resetting x[0].  We assume Mathematica  will automatically recompute x[1], x[2], and
so on, but it won't!  Look at the table below.  Only x[0] has changed!

x[0]=1;
Table[ {n, x[n]}, {n,0,5}];
TableForm[%]

In order to do the Newton calculation, you need to execute again ALL the commands that define the iteration, with the starting point changed.  This clears out the old values of x and redefines the relationship that will tell Mathematica  how to update the values:

(* Newton's method for f(x)=0. *)
(* Just define f, and a starting value x[0] *)

Clear[f,n,x]

f[x_]:=Cos[x]-x

x[0] = 1;

x[n_] := x[n] = x[n-1] - f[x[n-1]] / f'[x[n-1]]//N 

Table[ {n, x[n]}, {n,0,5}];
TableForm[%]

Problem 3a)

We are asked to carry out a computation for n=100, 200, 400, 1000.  How can we do this, since the list of numbers is not evenly spaced?

We can use a list to store the four values:

nvals={100,200,400,1000}

Now, for each value of n, we need to do a certain computation.  Here, I will just integrate 1/x^2 from 1 to n, where n is equal to nvals[[1]] through nvals[[4]]:

intvals=Table[ Integrate[ 1/x^2, {x,1,nvals[[i]]}],{i,1,4}]

And now I want a table of n, the integral, and the difference between the integral and 1:

tab=Table[ {nvals[[i]], N[intvals[[i]]], 
  N[Abs[1-intvals[[i]]]]}, {i,1,4}]
  
TableForm[tab]

Problem 3b)

To carry out the right and left Riemann sums, you should probably use the routines that were defined in Lab 4:

Clear[leftRiemannsum]
leftRiemannsum[f_,{x_,a_,b_,n_}]:=
 Block[{delx,i},
   delx=(b-a)/n;
   approx=N[ Sum[(f /.x->a+delx*i)*delx,{i,0,n-1}] ] ]

Clear[rightRiemannsum]
rightRiemannsum[f_,{x_,a_,b_,n_}]:=
 Block[{delx,i},
   delx=(b-a)/n;
   approx=N[ Sum[(f /.x->a+delx*i)*delx,{i,1,n}] ] ]