Message Boards Message Boards

Solving a problem using Newton's Method?

Posted 8 years ago

I'm having some trouble trying to solve this one problem using Mathematica and Newton's Method. I was able to type the following into Mathematica:

f[x_] := (9*Sin[x])/E^x^2 - x^2 + x - 1
iterations = 10; 
z = {0.2}; 
For[j = 1, j <= iterations, j++, a = z[[j]]; 
  z = Append[z, a - f[a]/Derivative[1][f][a]]]; 
Print[NumberForm[z, 10]]

When I try to shift enter for the problem, this comes up and I'm not sure what to do from here:

$RecursionLimit::reclim2: Recursion depth of 1024 exceeded during evaluation of Append[z,z[[1]]-(-1+z[[1]]-z[[1]]^2+9 E^-Power[<<2>>] Sin[z[[1]]])/(1+9 E^Times[<<2>>] Cos[Part[<<2>>]]-2 z[[1]]-18 E^Times[<<2>>] z[[1]] Sin[Part[<<2>>]])].

If anyone has any suggestions, they would be much appreciated. I have also attached my work to make it easier to read. Thanks again.

Attachments:
2 Replies

If you absolutely insist on doing the iteration procedurally, then like this:

f[x_] := 9 Sin[x]/Exp[x^2] - x^2 + x - 1     (* note clearer entry form for the function *)
iterations = 10;
z = {0.2};

fp[x_] = f'[x]      (* pre-evaluate the symbolic  derivative *)

For[j = 1, j <= iterations, j++,
 a = z[[j]];
 z = Append[z, a - f[a]/fp[a]]]

Print[NumberForm[z, 10]]

However, it's better to use a Do expression instead of a For expression, so you let Mathematica take care of the details of incrementing the counter j (the "j++" stuff):

z = {0.2};
Do[a = z[[j]]; z = Append[z, a - f[a]/fp[a]], {j, 1, iterations}]

However, as the answer by Frank Kampas shows, it's MUCH better to use the functional NestList expression: let Mathematica take care of essentially all details of the iteration, that is, of appending each iterate to the current list and incrementing the counter.

But why do you need to implement Newton's Method yourself? The built-in function FindRoot will use it by default:

FindRoot[f[x], {x, 0.2}] // NumberForm[#, 10] &

And if you want all the intermediate approximations, use Sow and Reap:

Flatten@Prepend[
   Last@Reap[FindRoot[f[x], {x, 0.2}, StepMonitor :> Sow[x]]], 0.2] //
  NumberForm[#, 10] &
POSTED BY: Murray Eisenberg
In[1]:= f[x_] = (9*Sin[x])/E^x^2 - x^2 + x - 1;

In[2]:= fp[x_] = D[f[x], x]

Out[2]= 1 - 2 x + 9 E^-x^2 Cos[x] - 18 E^-x^2 x Sin[x]

In[4]:= NestList[# - f[#]/fp[#] &, .2, 10]

Out[4]= {0.2, 0.0953315, 0.102137, 0.102156, 0.102156, 0.102156, \
0.102156, 0.102156, 0.102156, 0.102156, 0.102156}

In[5]:= f[%[[-1]]]

Out[5]= 0.
POSTED BY: Frank Kampas
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract