Mathematica Asked by Wizzerad on June 8, 2021
I would like to have a series of functions that depend one another, indexed by a number, and that are defined via a Do loop. However, Mathematica seems unable to replace the index in the loop. My trial code:
Do[
If[i == 1,
ff[i, x_, y_] := x + y;,
ff[i, x_, y_] := (x - y)*ff[i - 1, x, y];
];
, {i, 1, 2}];
ff[2, x, y]
Output:
(x – y) ff[-1 + i, x, y]
Desired output is however:
(x – y)(x + y)
This thing surprises me since if I manually define
ff[2, x_, y_] := (x - y)*ff[1, x, y];
then I get the desired output. It seems that the Do loop is not replacing inside the function.
Is this normal? 😮
In your Do
loop use Set
rather than SetDelayed
for the RHS to be evaluated.
Clear["Global`*"]
Using RSolve
to directly obtain a closed-form solution for the nth function
ff[n_, x_, y_] =
f[n] /. RSolve[{f[1] == x + y, f[n] == (x - y)*f[n - 1]}, f[n], n][[1]]
(* (x - y)^(-1 + n) (x + y) *)
Alternatively, using explicit recursion
f2[1] = x + y;
f2[n_] := f2[n] = (x - y)*f2[n - 1]
Generating a sequence from the recursion
seq = f2 /@ Range[5]
(* {x + y, (x - y) (x + y), (x - y)^2 (x + y), (x - y)^3 (x + y),
(x - y)^4 (x + y)} *)
Then using FindSequenceFunction
to generalize from the sequence, the result is identical to that provided by RSolve
FindSequenceFunction[seq, n] === ff[n, x, y]
(* True *)
Answered by Bob Hanlon on June 8, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP