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

Posted 1 year ago
1592 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
Sort By:
Posted 1 year ago
 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 1 year ago
 So smart! Thank you !!
Posted 1 year ago
 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 *)