In wanting to demonstrate the power of Mathematica, I wanted to show my 11-year-old son how we could validate that his sequences homework was correct. We could generate the next value in sequence in a simple expression, but when it came to repeatedly doing this (for the next 10 values), I got stuck.
We have seed list of values {0,2,2,4}
which we called seedlist
. The sequence is simply taking the last two numbers and adding them together to create the next number.
What I wanted to show was how we could generate an extended list for the first 10 (say) values e.g.
{0, 2, 2, 4, 6, 10, 16, 26, 42, 68}
In an attempt to append the next value into the list we did the following
Append[seedlist, (Extract[seedlist, 3] + Extract[seedlist, 4])]
Now I wanted to be able to recursively append to the list. So I tried several approaches as follows:
Tried to use a function and the called NestList:
rec[dat_, n_] := Append[seedlist, (Extract[seedlist, n] + Extract[seedlist, n - 1])] NestList[rec[#, i] &, seedlist, {i, 1, 10}]
This gave me an error "Non-negative machine-sized integer expected at position 3 in NestList[rec[#1,i]&,{0,2,2,4},{i,1,10}]"
After a bit more digging in the documentation, I then tried a simpler version
NestList[Append[ Rest[#], (Extract[#, 4] + Extract[#, 4 - 1])] &, seedlist, 7]
This worked to a degree but I got presented with the following list
{{0, 2, 2, 4}, {2, 2, 4, 6}, {2, 4, 6, 10}, {4, 6, 10, 16}, {6, 10, 16, 26},
{10, 16, 26, 42}, {16, 26, 42, 68}, {26, 42, 68, 110}}
This has all the answers, just not necessarily in the right places! This is, without necessarily knowing it, what I asked for in the above of course but not what I want to achieve.
I'd be really grateful for someone to point me in the right direction and get the correct list out. I have a feeling I'm fairly close with the last attempt, but I'd appreciate a nudge to solve this correctly.
NestList[Append[#, #[[-2]] + #[[-1]]] &, seedlist, 7]
$\endgroup$LinearRecurrence[{1, 1}, {0, 2}, 10]
is the built-in, by the way, orRecurrenceTable[{a[n + 1] == a[n] + a[n - 1], a[1] == 2, a[0] == 0}, a, {n, 0, 10}]
. (Much less pedagogical value to those.) $\endgroup$Append
function doesn't work in-place and so is quite slow:Nest[{#[[2, 1]] + #[[1]], #} &, {2, {0}}, 10] // Flatten // Reverse
$\endgroup$SequenceFoldList
did perform pretty well. $\endgroup$