For an assignment, I have to implement Newton's method using
Module
and a For
loop. So far, I have
newtMethod[guess_, fun_] :=
( Module[{k, x0, x1},
x0 = guess;
For[k = 1,
Abs[x1 - x0] >= .0001,
k = k + 1,
x1 = (x0 - fun[x0]/fun'[x0]);
If[Abs[x1 - x0] < 0, x0 = x1, x1 = x1];
x1]; Print[x1]])
When I run this, a strange message appears.
f[x_] := Sin[E^x];
newtMethod[2.5, f]
x1$5709
If I remove the
Print[x1]
part of the code, there's NO output entirely. What am I doing wrong here? Is there any meaning to the weird output? I think my error has to do with what I included in the
For
loop and what I defined x1
to be, but I'm not sure. Any tips?
Nest
,NestWhile
orFixedPoint
should be better choices. $\endgroup$Print
at all. Mathematica expressions likeModule
/Block
return their final result, so you'll getx1
from that, no printing necessary $\endgroup$