I have a confession to make. I kind of hate floating-point numbers. Sure, they're useful if you happen to be a computer, but if you're a human being your left scratching your head at situations like this:
129.95 * 100
# => 12994.999999999998
Not only does this fly in the face of mathematical harmony, it's also bad UX.
If a recipe told you to measure 0.37211927843 cups of flour, you would probably chuckle yourself about what an idiot the author was and proceeded to measure out a third of a cup.
Most people are able to think about fractions a lot more easily than they can think about arbitrary decimal numbers. So if your app is trying to communicate numbers to people, it might make sense to explore ways of expressing them as fractions.
Ruby's Rational
class is a great tool for working with rational numbers. It not only gives you the ability to do rational math, but it also lets you find simple fractions that approximate gnarly floating-point numbers. Let's take a look!
What are Rationals?
For our purposes, "rational numbers" is just a fancy way of saying "fractions." They have two parts: the numerator and denominator.
1/2 # Numerator is 1. Denominator is 2.
5 # Numerator is 5. Denominator is 1.
In Ruby, rational numbers get their own data type just like integers and floating-point numbers. There are a couple of ways to create a new rational:
3/2r # This syntax was introduced in Ruby 2.1
1.5.to_r # Floats can be converted to rationals via `to_r`
"3/2".to_r # ...so can strings
Rational('3/2') # This is how we had to do things in the olden days
Rational(3, 2) # ...see how hard life was?
Simple math
When you add, subtract, multiply, or divide two rational numbers the result is also rational.
2/3r + 1/3r
# => (1/1)
2/3r - 1/3r
# => (1/3)
2/3r * 1/3r
# => (2/9)
(2/3r) / (1/3r) # We need parens here to avoid confusing the interpreter
# => (2/1)
All of the other math operators pretty much act like you would expect too: **
, >
, <
, etc..
The general rule is that both of the inputs have to be fractions in order for the result to be a fraction. The one exception I could find is with integers. Since all integers are rational, Ruby does the smart thing and assumes everyone a rational output:
2/3r + 2
# => (8/3)
Approximations
One of the most useful things about rational numbers is that they allow us to approximate and easily do calculations in our heads. In order to take advantage of this we need to keep our fractions simple. 3/2
instead of 3320774221237909/2251799813685248
.
Fortunately, Ruby gives us an easy way to convert these precise-but-ugly numbers into approximate yet pretty numbers. I'm talking about the rationalize
method.
Here's what it looks like:
# Precise but ugly
(1.47472).to_r
=> (3320774221237909/2251799813685248)
# Less precise, but pretty
(1.47472).to_r.rationalize(0.05)
=> (3/2)
The rationalize method has one argument. It specifies the tolerance – the amount of precision that you're willing to trade for simplicity.
The method finds a number with the lowest denominator within your tolerance. Here's what I mean:
# What's the number with the lowest denominator between 5/10 and 7/10?
(6/10r).rationalize(1/10r)
# => (1/2)
# What's the number with the lowest denominator between 11/20 and 13/20?
(6/10r).rationalize(1/20r)
=> (3/5)
# ..and between 1/10 and 11/10?
(6/10r).rationalize(1/2r)
=> (1/1)
Cruder approximations
If all you need to do is find an integer or floating-point number that corresponds to the fraction, you've got several options.
# Return the nearest integer.
(6/10r).round
# => 1
# Round down
(12/10r).to_i
# => 1
Limitations of Rationals
There are a few limitations to be aware of when working with rational numbers and Ruby. Of course you can't divide by zero:
4/0r
ZeroDivisionError: divided by 0
And you will run into some strange behavior if you try to treat irrational numbers as rational.
# Umm, isn't the square root of 2 irrational?
Rational(Math.sqrt(2))
# => (6369051672525773/4503599627370496)
# And I'm pretty sure PI is irrational as well.
Rational(Math::PI)
# => (884279719003555/281474976710656)
We might expect that asking Ruby to treat an irrational number is rational would raise some kind of exception. But unfortunately Ruby doesn't seem to be smart enough to do this. Instead, it converts the floating-point approximations of these irrational numbers into rationals. It's not a huge problem, but something to be aware of.