From: Florian Frank Date: 2009-11-19T21:04:40+09:00 Subject: Re: Exact (LISP-ish) calculations in Ruby? Aldric Giacomoni wrote: > And I just read up on the process of 'continuing fractions' which can be > used find fractions / estimates of irrational numbers down to the nth > decimal. I wonder how we can know that, for instance, 1.41421 (etc) is > sqrt(2) ... ? > > Ah, mathematics. > I had to implement them for my bullshit library (which has grown to include half a math library by now, ugh): http://github.com/flori/bullshit/blob/master/lib/bullshit.rb#L20 require 'bullshit' # pardon my french include Bullshit >> ContinuedFraction.for_a { |n| n == 0 ? 1 : 2 }[] # => 1.4142135623731 They are rather fascinating. They can be used to implement functions as well, here's the atan function: atan = ContinuedFraction.for_a do |n, x| n == 0 ? 0 : 2 * n - 1 end.for_b do |n, x| n <= 1 ? x : ((n - 1) * x) ** 2 end >> atan[1] # => 0.785398163397448 Now, it's easy to approximate pi as well: pi = lambda { 4 * atan[1] } >> pi[] # => 3.14159265358979 As you can imagine I had a lot of fun playing with them. ;) -- Florian Frank