[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: Exact (LISP-ish) calculations in Ruby?
From:       "Florian Frank" <flori () ping ! de>
Date:       2009-11-19 12:04:40
Message-ID: 4B053375.7040601 () ping ! de
[Download RAW message or body]

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


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic