I have the following code:
f0[x_]:=0.1Exp[-x]+1.3;
f1[x_]:=f0[x](1+Sqrt[1/(10000f0[x])]);
f2[x_]:=f1[x](1+Sqrt[1/(10000f1[x])]);
f3[x_]:=f2[x](1+Sqrt[1/(10000f2[x])]);
f4[x_]:=f3[x](1+Sqrt[1/(10000f3[x])]);
f5[x_]:=f4[x](1+Sqrt[1/(10000f4[x])]);
f6[x_]:=f5[x](1+Sqrt[1/(10000f5[x])]);
Plot[{f0[x],f1[x],f2[x],f3[x],f4[x],f5[x],f6[x]},{x,0,2}]
Note that the $f_n$ are calculated iteratively, with $f_{n-1}$ being used to calculate $f_n$. This produces the following graph:
However, it's a pretty inefficient way to write code, especially when your functions are more complicated than this. So I figured I could do an actual iteration:
f0[x_]:=0.1Exp[-x]+1.3;
For[iter=1,iter<=6,iter++,
f1[x_]:=f0[x](1+Sqrt[1/(10000f0[x])]);
f0[x_]:=f1[x];
];
Plot[{f0[x],f1[x]},{x,0,2}]
However, this causes Mathematica to get stuck in a recursion loop because of the SetDelayed
:
As a rule, I avoid using Set
for functions because SetDelayed
behaves better. Should I just use Set
in this case to avoid this problem? Or is there a smarter way to code the iteration that I haven't thought about?
I suppose I could define an array of functions:
f=ConstantArray[0,7];
f[[1]][x_]:=0.1Exp[-x]+1.3;
For[iter=1,iter<=6,iter++,
f[[iter+1]][x_]:=f[[iter]][x](1+Sqrt[1/(10000f[[iter]][x])]);
];
Plot[{f[[1]][x],f[[2]][x],f[[3]][x],f[[4]][x],f[[5]][x],f[[6]][x],f[[7]][x]},{x,0,2}]
I don't even know whether that would work (haven't tried it). Again, though, even if it does work, it's a pretty inefficient way to code; Mathematica would save seven functions in its memory instead of two.
f[1][x_] = 0.1 Exp[-x] + 1.3; For[iter = 1, iter <= 6, iter++, f[iter + 1][x_] = f[iter][x] (1 + Sqrt[1/(10000 f[iter][x])])]; Plot[Evaluate[Table[f[i][x], {i, 1, 7}]], {x, 0, 2}]
$\endgroup$Set
causes things to evaluate instantly rather than later (when first invoked in a calculation), occasionally functions do silly things which are not always easy to debug, especially when you use loops. I couldn't give you an example right now, since it's a fairly uncommon thing and I can't remember any specific case in which it's happened to me, but ita has happened a few times, whereas this is the first real problem I've had withSetDelayed
. $\endgroup$