I am probably missing something obvious, but I am stuck. I am writing a code on Mathematica for Newton's method, and I need to print out a table for the iteration, approximation root, residual, and the absolute value of the difference between the current and previous approximation. I set a threshold already, and I am pretty much done. However, I can't print out the table. I printed out the values for each iteration in separate lists. I want to print them out in tuples of 4 so that I can make the table and use the command Grid. I just can't find a command that does it. Here is my code and my output. I just need my values in a table. I am attaching my code as a picture to this post. PLEASE HELP! Thank you
2 Answers
$\begingroup$
$\endgroup$
f[x_] := x*Exp[-x] - .16064
newt[x_] := x - f[x]/f'[x]
m = {}; x = 3; err = 10^-10;
Do[x0 = x; x = newt[x0];
m = Flatten[{m, {{i, x0, x, f[x], Abs[x - x0]}}}, 1];
If[Abs[x - x0] <= err, Break[]];, {i, 100}]
m // TableForm
$\begingroup$
$\endgroup$
I recommend code similar to this
ClearAll[x, x0, x1, i, f];
f[x_] := x/Exp[x] - 0.16064;
newt[x_] := x - f[x]/f'[x];
i = 0; x0 = 0; x1 = 3;
Reap[ While[i <= 100 && Abs[x0 - x1] > 10^-5,
x0 = x1; x1 = newt[x0]; i++;
Sow[{i, x0, x1, f[x1], Abs[x0 - x1]}]
]][[2, 1]]
Of course, there are other ways in Mathematica but this is easy.
Print
tosses its result outside the Mathematica universe, making it hard to recover. For this kind of problem, I usually write a function that takes the result of an iteration and produces a new result, and then feed it (along with a starting state) toNestWhileList
. $\endgroup$f[{thing1_,thing2_}]:={new1,new2}
wherenew1
andnew2
are expressions that compute the new values from the old ones,thing1
andthing2
. $\endgroup$NestWhileList
manages the list construction for you, so you don't have to worry about how to do it. Usually, in Mathematica, building lists step by step in code is the hard way to do it. $\endgroup$