```⍝ Tail-recursive Fibonacci:

⎕io←1

fibonacci¨⍳10
1 1 2 3 5 8 13 21 34 55

{⎕io←0 ⋄ +/!∘⌽⍨⍳⍵}¨ ⍳10                     ⍝ NN & JF
1 1 2 3 5 8 13 21 34 55

{+/{⍵!⌽⍵}(⍳⍵)-⎕io}¨⍳10                      ⍝ (John R. Clark)
1 1 2 3 5 8 13 21 34 55

(.5×1+5*.5)∘{((⍺*⍵)-(1-⍺)*⍵)÷5*.5}¨⍳10      ⍝ Binet's formula (Dick Bowman).
1 1 2 3 5 8 13 21 34 55

⍬∘⍴∘⊃∘(⊢∘⌽∘(+\)/)∘(,∘(⊂0 1))∘⍳  ¨⍳10
1 1 2 3 5 8 13 21 34 55

(0.5×1+1 ¯1×5*0.5)∘{(-⌿⍺∘.*⍵)÷-/⍺} ⍳10      ⍝ Binet (PMH)
1 1 2 3 5 8 13 21 34 55

{1∧+∘÷/0,⍵/1}¨0 to 10                       ⍝ continued fractions
0 1 1 2 3 5 8 13 21 34 55

fib←{                                       ⍝ Sullivan
z←0.5×1+s←5*0.5
((z*⍵)-(2○○⍵)×z*-⍵)÷s
}

rnd←3∘{(10*-⍺)×⌊0.5+⍵×10*⍺}                 ⍝ round to 3 decimal places.

rnd fib ¯5 ¯4.5 to 5
5 0.051 ¯3 0.083 2 0.134 ¯1 0.217 1 0.352 0 0.569 1 0.92 1 1.489 2 2.41 3 3.899 5

Fibonacci←{⎕io ⎕ml←0 1  ⍝ First ⍵ fibonacci numbers.
s←⎕ns''             ⍝ Class
s.(f←{⍺←⎕this ⋄ ⍺.i<2:⍺.n ⋄ ⊢⍺.n←+/⍺.a[⍺.i-1+⍳2].n})    ⍝ Method
v←⎕ns¨⍵⍴s           ⍝ Collection
v.i←⍳⍵              ⍝ Item number
v.n←⍵↑0 1           ⍝ Initialize
v.a←⊂v              ⍝ Each knows all
v.b←(1+⍳⍵)⍴¨⊂v      ⍝ Each knows self and previous?
v.f 0               ⍝ Compute
}

Fibonacci 10            ⍝ P. Mansour
0 1 1 2 3 5 8 13 21 34

fibcode←{               ⍝ fibonacci-coding of number ⍵.

pair←{              ⍝ fib-pair
n←+/⍵           ⍝ next term.
⍺<n:⍵           ⍝ term large enough: finished.
⍺ ∇ 1↓⍵,n       ⍝ next pair
}                   ⍝ :: i j ← n ∇ i j

vec←{               ⍝ ⍺ is accumulator.
n(i j)←⍵        ⍝ remaining number and current fib pair.
i=0:⍺,1         ⍝ exhausted radix list: accumulator, sentinel.
f←(j-i),i       ⍝ next fib pair.
t←n≥j           ⍝ next term and
r←n-t×j         ⍝   remainder.
(t,⍺)∇ r f      ⍝ accumulated fib-coding.
}                   ⍝ :: [b] ← [b] ∇ n(i j)

⍬ vec ⍵,⊂⍵ pair 0 1 ⍝ fi
}

↑⍕∘fibcode¨0 to 10      ⍝ fibonacci codding of 0..10
1
1 1
0 1 1
0 0 1 1
1 0 1 1
0 0 0 1 1
1 0 0 1 1
0 1 0 1 1
0 0 0 0 1 1
1 0 0 0 1 1
0 1 0 0 1 1

2 1∘fibonacci¨ 0 to 10      ⍝ Lucas sequence.
2 1 3 4 7 11 18 29 47 76 123

Back to: code

Back to: Workspaces
```