Message Boards Message Boards

GROUPS:

How to realize the function Nest[] with two replaced variables?

Posted 6 months ago
773 Views
|
5 Replies
|
4 Total Likes
|

How to realize Nest[{a,b,#1,#2} &, ]? For example, #1 should be replaced by x, and #2 by y simultaneously or even respectively ?

5 Replies

I do this frequently. The easy way is to define a function that deconstructs a single composite argument with a pattern:

f[{a_, b_}] := {a + 1, b + a}
Nest[f, {0, 0}, 10]
(* {10, 45} *)

If I'm feeling fussy, I'll use a custom wrapper symbol rather than List:

f[state[a_, b_]] :=state[ a + 1, b + a]
Nest[f, state[0, 0], 10]
(* state[10, 45] *)
Posted 6 months ago

So smart! Thank you !!

Another approach for John Doty's example that utilizes less pattern matching could be

Nest[{#[[1]] + 1, #[[2]] + #[[1]]} &, {0, 0}, 10]

Compare these timings

f[{a_, b_}] := {a + 1, b + a}
r1 = Nest[f, {0, 0}, 100000]; // RepeatedTiming // First
r2 = Nest[{#[[1]] + 1, #[[2]] + #[[1]]} &, {0, 0}, 100000]; //  RepeatedTiming // First
r1 == r2
(* 0.087 *)
(* 0.0056 *)
(* True *)

Of course, there are better methods for linear recurrences, e.g.,

r3 = MatrixPower[N@{{1, 0, 1}, {1, 1, 0}, {0, 0, 1}}, 100000, {0, 0, 1}][[1 ;; 2]]; // RepeatedTiming // First
r1 == r3
(* 8.39*10^-6 *)
(* True *)
Posted 6 months ago

Ah! It's just what I want ! Thank you !!

You're welcome.

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract