2

Is there a way to change how numbers are displayed in the output from RecurrenceTable?

stepSize = .5; stepNum = 5; t0 = -1; y0 = -1; f[y_, t_] := y^2 - t;

Grid[Prepend[
RecurrenceTable[{k[n + 1] == k[n] + 1, t[n + 1] == t[n] + stepSize, 
y[n + 1] == m[n]*stepSize + y[n], y[0] == y0, k[0] == 0, t[0] == t0,
m[0] == f[y[0], t[0]], 
m[n + 1] == f[m[n]*stepSize + y[n], t[n] + stepSize]}, {k, t, y, 
m}, {n, stepNum}], {"k", "t", "y[t]", "m"}], Frame -> All]

RecurrenceTable output

For example, in the output above RecurrenceTable changes the integer values in the first column, k, to floating point. I'd like for the k column (step number) to display as an integer. I've tried applying functions like Style, IntegerPart, etc. in RecurrenceTable as could be used in Table, but they generate errors.

Also, I used RecurrenceTable here instead of Table because one row element requires the results of a previous row's information in its calculation. This kind of table is fairly simple to create in Excel. Is there a simpler/easier way to emulate this kind of Excel table functionality in Mathematica? RecurrenceTable seems like overkill for this purpose.

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
BCott
  • 89
  • 5

1 Answers1

3

You can Rationalize only the first member of each list returned by RecurrenceTable, e.g. by Applying the following modifier function:

{Rationalize@#1, ##2} &

at each level. #1 represents the first argument in the sequence supplied to a function; ##2 represents the sequence of all arguments, starting with the second one (see SlotSequence).

In other words:

results = RecurrenceTable[
  {k[n + 1] == k[n] + 1,
   t[n + 1] == t[n] + stepSize,
   y[n + 1] == m[n]*stepSize + y[n],
   y[0] == y0, k[0] == 0, t[0] == t0, m[0] == f[y[0], t[0]],
   m[n + 1] == f[m[n]*stepSize + y[n], t[n] + stepSize]},
  {k, t, y, m}, {n, stepNum}
 ];

{Rationalize@#1, ##2} & @@@ results

(* Out:
{{0, -1., -1., 2.}, {1, -0.5, 0., 0.5}, {2, 0., 0.25, 0.0625}, {3, 0.5, 0.28125, -0.420898}, 
 {4, 1., 0.0708008, -0.994987}, {5, 1.5, -0.426693, -1.31793}}
*)

You can use this in your grid expression for further formatting:

Grid[
  Prepend[
    {Rationalize@#1, ##2} & @@@ results,
    {"k", "t", "y[t]", "m"}
  ],
  Frame -> All
]

Mathematica graphics

MarcoB
  • 67,153
  • 18
  • 91
  • 189