开发者

Mathematica HELP with While and Module command

开发者 https://www.devze.com 2023-02-22 05:35 出处:网络
Does this equat开发者_JAVA技巧ion work for all sequences f[n]? f[n_] :=Module[{x = intial value, y = 0, i = 0},

Does this equat开发者_JAVA技巧ion work for all sequences f[n]?

f[n_] :=  Module[{x = intial value, y = 0, i = 0},

            While[i++ < n, {x, y} = {y, equation}]; y]

Specifically, I'm looking at the equation 6*n*f[n]=f[n-1]+n! with initial condition f[0] = 7. But, I'd like the solution to general, so that I can apply it to other equations. And, I'd like to use Module and While.

thank you.


The cleanest and most common way to implement a recurring sequence is to just define f using memoization, "remembering" terms as they are computed for efficiency:

f[0] = 7
f[n_Integer?Positive] := f[n] = (f[n - 1] + n!)/(6 n)

Then:

In[29]:= Table[f[n], {n, 0, 6}]

Out[29]= {7, 4/3, 5/18, 113/324, 7889/7776, 941009/233280, 168902609/8398080}

If you're not required to program the recurrence yourself, you could also use RecurrenceTable to generate terms directly without defining f:

In[30]:= RecurrenceTable[{a[0] == 7, 6 n a[n] == a[n - 1] + n!}, a, {n, 6}]

Out[30]= {7, 4/3, 5/18, 113/324, 7889/7776, 941009/233280, 168902609/8398080}


So you want to calculate the sequence:

f(n) = (f(n-1) + n!) / (6 * n)

One way to implement it is:

f[n_] := Module[{values},
       values = Table[0, {n}];
       values[[1]] = 7;
       Do[values[[i]] = (values[[i-1]] + (i-1)!) / (6 * (i-1)), {i, 2, n}]
       values];

Or equivalently:

f[n_] := Module[{values, i = 2},
       values = Table[0, {n}];
       values[[1]] = 7;
       While[i <= n, values[[i]] = (values[[i-1]] + (i-1)!) / (6 * (i-1)); i++];
       values];

There are much more efficient ways though.

I forget the differences of Bock and Module off hand, but they're very similar.

0

精彩评论

暂无评论...
验证码 换一张
取 消