1

I have written the Mann iteration's code for the mapping $\frac{z}{1+z^2}$, in Mathematica, but it is very slow. In fact it needs more than 200 seconds for obtaining 17th iteration, while Matlab does 100 iterations of the the Mann iteration in a second. Would you please tell me what is wrong with my code?

Clear[x, z, n, lambda, f]
For[n = 1; x[1] := 1;
lambda := 1/2; f[z_] := z/(1 + z^2), n < 21, n++,
x[n_] := (1 - lambda) x[n - 1] + lambda f[x[n - 1]]; Print[Timing[N[x[n]]]]]
morapi
  • 67
  • 6

2 Answers2

6

The following approach might be more "standard Mathematica":

Clear[f]
f[z_] := z/(1 + z^2)

lambda = 0.5;

Clear[x]
x[1] = 1;
x[n_] := x[n] = (1 - lambda) x[n - 1] + lambda f[x[n - 1]]

list = Table[x[n], {n, 1, 150}];
ListPlot[list, PlotRange -> All]

Memoization (i.e. saving intermediate values of x[n], see also Q2639) appears to help considerably. Execution is then practically instantaneous even for large $n$.

It also helps greatly to get away from symbolic calculations: instead of lambda = 1/2, use the machine-precision value lambda = 0.5.

Mathematica graphics

More in general, you might also want to take a look at:

MarcoB
  • 67,153
  • 18
  • 91
  • 189
2

note it is a little faster to march it out directly without recursion:

 list = NestList[ (1 - lambda) # + lambda f[#] & , 1 , 149]
george2079
  • 38,913
  • 1
  • 43
  • 110