Forum Discussion
Viz
Jan 05, 2021Brass Contributor
Lambda Example: Generate Fibonacci series
In this post, I would like to explain how I have used Lambda to create a function to generate a Fibonacci series array. This example can also be used to understand how to create an array where th...
lori_m
Jan 06, 2021Iron Contributor
Viz I should have replied here instead of the other post for further discussion.
Have also tweaked recursive formula for the n=1 case.
FIB:
=LAMBDA(n,
IF(n<=2,
SEQUENCE(n,,0),
LET(b,FIB(n-1),
IF(SEQUENCE(n)<n,b,INDEX(b,n-1)+INDEX(b,n-2))
)))
- VizJan 06, 2021Brass Contributor
Wow! your solution is super elegant!
I was initially trying something closer to your first solution but I could not crack the logic to extend the size of array. And the algorithm I used to extend the array made the function very slow.
I am still getting my head around your function to understand how the array is getting extended. But thank you very much for sharing these solutions. It was very useful.
- SergeiBaklanJan 06, 2021Diamond Contributor
If add error handling as
=LAMBDA(n, IF(n<>INT(n),"use integer as argument", IF(n<=2, SEQUENCE(n,,0), LET(b,FIB(n-1), IF(SEQUENCE(n)<n,b,INDEX(b,n-1)+INDEX(b,n-2)) ))))
it returns errors message as expected for FIB(10.1), but the spill as
for FIB(10+1e-14). Correction could be
=LAMBDA(n, IF(n<>INT(n),"use integer as argument", LET(m, INT(n), IF(m<=2, SEQUENCE(m,,0), LET(b,FIB(m-1), IF(SEQUENCE(m)<m,b,INDEX(b,m-1)+INDEX(b,m-2)) )))))