Message Boards Message Boards

GROUPS:

Create a table within a while loop in Mathematica?

Posted 27 days ago
215 Views
|
4 Replies
|
0 Total Likes
|

So I am working on a code for Newton's method. I have the newton's method down, but I cannot get the results in a table format. I attached a screenshot of my code and the output to this post. I am able to print out the results, each iteration, the x value, the f(x), and the difference between my current and previous x's. However, I am trying to create a table, and so forth till my loop ends, like this:

i x f(x) Abs[] 1 value value value 2 value value value 3 ..... enter image description here I know I get three separate lists, but what is the command that I need to put it in 3-tuples, like {{x, y, z, t}, {x, y, x, t}...} so that I can create my table. I tried using AppendTo, by creating an empty list and appending values to the list, but that does not work. If anyone can help, I would immensely appreciate it!

Thank you!

4 Replies

I would do it with NestWhileList:

f[x_] := x*Exp[-x] - 0.16064;
newt[x_] := x - f[x]/f'[x];
values = NestWhileList[newt, 3, Abs[#1 - #2] > 10^(-5) &, 2, 100]
Differences[values]
Grid[Transpose[{Range[Length[values] - 1], Rest[values], 
   Abs@Differences[values]}]]

I'll ignore using nest, you can add that later.

First you want to remove the semicolon and print so that {i,xn,f(xn),abs(xn-xn-1)} is the last statement in the loop before last right bracket. By doing so the Block will exit with the statement as Out[]. Also, you can use Table instead of While: avoid While.

Now you have a block exit with a list of lists. {{list},{list},...} which can be accessed with Part[list,spec].

You can re-arrange the list with Partition[list,spec] if you need it in a different grouping.

Posted 26 days ago

I think I know what you are talking about, but I thought you need while though. While you have a set number of iterations do so and so. I read about Newton's Method. I will try what you said, but can AppendTo work? My professor said to create an empty list and append what I have in the loop to the list. I tried doing that, but I got nothing.

Grid is a text formatting function. It would be better if you "do your math" first then provide the result as as input to Grid (rather than attempting math inside Grid[do my math]). You'll find many Mathematica functions may not do math the same within their args because there are things like "argument holding".

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