# The use of NestList

After read Michael answer, code use NestList to compute and feed in numerical integration. I want to learn this idea into my code.

In the NestList document, this function have three parameter, eg. f, expr, n.if define f, NestList seems to map expr to f[expr],'f[f[expr]]',... n times.

So I refer Michael code,

deltat = 1*^-3;
integrator[x_, y_, {x0_, y0_}] := {x, y} /.
FindRoot[{x - x == deltat,
y - y == deltat}, {{x, x0}, {y, y0}}];
integrator[x, y, {0, 0}]


And

NestList[integrator[x, y, {y, y}], {x, y}(* condition *), 4]


I want calculate 4 times nesting, at beginning, $$x0,y0$$ is the initial value, and call integrator to get $$x1,y1$$, and repeat, $$x1,y1$$ as initial point, call integrator again, and find root again. Above code's output is not what I expected.

I still don't understand NestList enough, I seem to only know this form, but don’t know how to use it for specific problems.

Update(I still have a bugs with my code, sad, Others gave the right answer, but I still failed)

ClearAll[integrator, myintegrator, stepintegrator];
deltat = 1*^-3;
integrator[x_, y_, {x0_, y0_}] := {x, y} /.
FindRoot[{x - x == deltat,
y - y == deltat}, {{x, x0}, {y, y0}}];
(*integrator[x,y,{0,0}]*)

myintegrator[x_, y_][x0_,
y0_] := {Sequence @@ integrator[x, y, {x0, y0}]}
stepintegrator = myintegrator[x, y];
NestList[stepintegrator, {0, 0}, 2]

• Let's say: f[{x_, y_}] := {x + 1, y + 1}; is a function that takes a list and returns a list. Execute: NestList[f, {x, y}, 4] to see the result.
– Syed
Nov 18, 2021 at 17:39
• read the answer code a bit more closely—you'll notice Michael uses a function as the first argument to nestlist, by expecting myIntegrator[param1, param2,..][{x0, y0}] to return a point in the trajectory. (note that this is of the form f[a][b]f[a] is a function!) He then takes stepIntegrator = myIntegrator[param1, param2,..], which is, as mentioned, a function. NestList always takes a function as its first argument; see the docs. You should use integrator[x_, y_][{x0_, y0_}] and integrator[x,y] in NestList instead. Nov 18, 2021 at 17:43
• @thorimur Thank you, it is my first time to know function as ‘function[para,para][x,y]’, you are right, I should read more carefully, it is details can’t be ignored!
– Ben
Nov 18, 2021 at 17:52
• @Syed I have try this code, it doesn’t work when I need update condition, the problem maybe due to ‘f’ should have second parameters like ‘f[para,para][x,y]’ in my example.
– Ben
Nov 18, 2021 at 17:57
• It is a simple example to show how NestList works. NestList can keep applying the function at the last result.
– Syed
Nov 18, 2021 at 18:04