rationals | rationals2 | fractions | fractions2 | habiter

continued fractions

F = [a0;a1,a2,...,an]
  = a0 + 1
         a1 + 1
              a2 + 1
                   ... 1
                       an

algorithm

a = [a0, a1, ..., an-1]
u(0) = a[0]
u(n) = 1 / (a[n] + u(n-1))

code

{def frac
 
{def frac.r
 {lambda {:f :u :i}
  {if {= :i 0}
   then {+ {:f 0} :u}  
   else {frac.r :f
                {/ 1 {+ {:f :i} :u}}
                {- :i 1}}}}}
 
{lambda {:f :n}
  {frac.r :f 1 :n}}} 
->  frac

computing φ, √2, √3, e, π, ...

φ = [1 1 1 1 1 ...]
{frac {lambda {:n} 1}
 40}
-> 1.618033988749895
   1.618033988749895

√2 = [1 2 2 2 2 ...]
{frac {lambda {:n}
        {if {= :n 0} then 1 else 2}}
 20}
-> 1.4142135623730954
   1.4142135623730951

√3 = [1 1 2 1 2 1 2 ...]
{frac {lambda {:n}
        {if {= :n 0}
         then 1
         else {if {= {% :n 2} 0}
         then 2
         else 1}}}
 30}
-> 1.7320508075688772
   1.7320508075688772

e = [2 1 2 1 1 4 1 1 6 1  1  8 ...]
{frac {lambda {:n}
         {A.get :n {A.new 2 1 2 1 1 4 1 1 6 1 1 8 1 1 10 1 1 12 1 1 14}}}
 10} 
-> 2.7182818284590455
   2.718281828459045 

π = [3 7 15 1 292 1 1 1 2 1 3 1 14 2 1 1 2 2 2 2]
{frac {lambda {:n}
         {A.get :n {A.new 3 7 15 1 292 1 1 1 2 1 3 1 14 2 1 1 2 2 2 2}}}
 15}
-> 3.141592653589793
   3.141592653589793
bt