0
$\begingroup$

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 enter image description here

$\endgroup$
4
  • 2
    $\begingroup$ 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) to NestWhileList. $\endgroup$
    – John Doty
    Commented Feb 24, 2019 at 22:09
  • $\begingroup$ what do you mean write a function? I want to try saving everything, but I do not know how. I tried creating an empty list and then appending my results from the while loop to that list. It does not work. Is there a better format to do that? $\endgroup$ Commented Feb 24, 2019 at 23:00
  • $\begingroup$ Something like f[{thing1_,thing2_}]:={new1,new2} where new1 and new2 are expressions that compute the new values from the old ones, thing1 and thing2. $\endgroup$
    – John Doty
    Commented Feb 24, 2019 at 23:03
  • 1
    $\begingroup$ 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$
    – John Doty
    Commented Feb 24, 2019 at 23:07

2 Answers 2

1
$\begingroup$
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

fig1

$\endgroup$
0
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.