Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Decimal to fraction in Ruby

// Adds a 'to_fraction' method to Float. Eg. 0.5.to_fraction => [1,2]

class Float
  def number_decimal_places
    self.to_s.length-2
  end
  
  def to_fraction
    higher = 10**self.number_decimal_places
    lower = self*higher

    gcden = greatest_common_divisor(higher, lower)

    return (lower/gcden).round, (higher/gcden).round
  end
  
private

  def greatest_common_divisor(a, b)
     while a%b != 0
       a,b = b.round,(a%b).round
     end 
     return b
  end
end

Convert a number to its closest fraction

Sometimes, I need to find a ratio approximation of a number.
Like 640 / 480 (vga) or similar number. I learn about farey
series a few years ago (1994).
The idea is actually quite simple.
>>> farey(math.pi,100)
(22, 7)

Get the implementation here.
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS