So I'm trying to use Newton's method to find the root of a function. The code works, what isn't working is my absolute error calculation. What I need is to subtract my past iteration from the current one. Unfortunately #x[n - 1] - x[n]
isn't working for some reason. What can be done?
2 Answers
With x[n_]=...
you define a function (and you redefine it in each iteration). Removing the subscore should help: x[n]=...
defines a Downvalue
of x
. This way, x
works like a hash table indexed over n
.
Note that this does not define an array in Mathematica. Indexing into an array is done with double brackets [[ ]]
(see documentation of Part
).
You need to collect your x[n]
in an object. You then Abs[Differences[object]]
.
I would strongly urge consideration of alternatives to For
loops.
There are number of alternatives to For
loops in Wolfram Language (Mathematica). There are a number of resources on this site, e.g. Alternatives to procedural loops and iterating over lists in Mathematica.
These are invaluable resources to consider.
For this case, for example for your function:
f[x_] := Exp[x] + 2^(-x) + 2 Cos[x] - 6
You could use NestList
to implement Newton's method.
nm[f_, x_, x0_, n_] := NestList[x - f[x]/f'[x] /. x -> # &, x0, n]
You could then play use the output as you wish. For "fun":
exam[a_, x_, n_, l_, r_, b_, t_] :=
Module[{newt = nm[f, x, a, n], im, tab},
im = Flatten[{Arrow[{{#1, 0}, {#1, f[#1]}}], Red,
Arrow[{{#1, f[#1]}, {#2, 0}}]} & @@@ Partition[newt, 2, 1]];
tab = TableForm[Thread[{Rest@newt, Abs[Differences[newt]]}],
TableHeadings -> {Range[n], {"\!\(\*SubscriptBox[\(x\), \(n\)]\)",
"|\!\(\*SubscriptBox[\(x\), \(n - \
1\)]\)-\!\(\*SubscriptBox[\(x\), \(n\)]\)|"}}];
Table[Column[{Show[Plot[f[x], {x, l, r}], Graphics[im[[1 ;; j]]],
PlotRange -> {b, t},
PlotLabel -> Row[{"\!\(\*SubscriptBox[\(x\), \(0\)]\) =", a}]],
tab}], {j, Length[im]}]]
The image was made using:
Export["nme.gif", exam[1.5, x, 4, 1.4, 2, -1, 1], “AnimationRepetitions" -> Infinity]
-
$\begingroup$ +1! Very cool & educational answer. Can you clarify how long it takes to run? That is, I am curious if one can use
Manipulate
with something like this to interactively show students how their initial parameter (educated guess) influences the amount of steps necessary? $\endgroup$ Sep 5, 2020 at 21:34 -
$\begingroup$ @CATrevillian you could wrap in Manipulate. There will better ways to code this. I was just appealing to consider alternatives to For. Thank you for feedback. $\endgroup$– ubpdqnSep 5, 2020 at 23:06
x[n]
function doesn’t at all depend on n? As well, you are redefininga
, which is the main argument being used in yourx[n]
function. Also, please edit your question with the code in a code-block, such that other users can copy & paste said code. This is a better method than containing it in an image. $\endgroup$