« learns_to: A None-Too-Brief Introduction to Partials
Main
Back from the Lull »
learns_to divide by zero
Is it just me, or is it fun when you get to break basic rules you learned in school? And more fun the younger you learned them? Not sharing, not looking both ways before crossing the street, not eating cookies and ice cream in bed before going to sleep without brushing your teeth, and so on.
Last week, at work, I got to divide by zero.
Here's the setup. We wanted to make sure that some value was positive, but we couldn't use a normal greater-than-zero comparison because the Rails situation demanded either a range or an array (it was a validates_inclusion_of :some_value, :in => range, if you're curious).
Anyway, there's the problem: how do you get a range that includes all numbers from zero on up? In mathematical terms, what I wanted was: [0,∞). So, I needed infinity. After staring blankly for awhile, it occurred to me: divide by zero! That would certainly produce something odd, possibly even infinity. I tried it:
>> 1/0
ZeroDivisionError: divided by 0
from (irb):16:in `/'
from (irb):16
Ow, snap! Ruby's not having any of that. But don't fear, not all options are exhausted. There are different kinds of one, different kinds of zero. And it turns out, that's the key. For some reason, Ruby won't even think about dividing an integer by zero, but give it a float, and it gets creative:
=>> 1.0/0
=> Infinity
Infinity! What's this? It looks a lot like a constant, but no:
>> (1.0/0).class
=> Float
It's a float. Which is just what ranges take as their bounds. And now we've got it:
>> range = 0..1.0/0
=> 0..Infinity
>> range.include?(1000000000000000000 * 100000000000000000)
=> true
Nifty? Subversive? Dangerous? Maybe. Fun? I think so.
Tagged: infinity, ruby, rails, programming, division, zero, numbers, mathPosted by Greg at April 6, 2006 12:19 AM
Comments
As a non-fun person (read android):
This is part of the IEEE 754 standard for floats, and ruby obeys it as every other modern language out there does.
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/5156
Posted by: Finger in Tim Harrington's Nose at April 6, 2006 11:55 AM
If you're validates_inclusion_of :foo, :in => RANGE, why can't you make that range positive?
If it just needs to be a positive number, why not validates_inclusion_of :foo, :minimum => 0 ?
Posted by: matt at April 6, 2006 12:07 PM
ack, nevermind on that last one. my lack of coffee while reading my morning rss caused me to misread the api.
Posted by: matt at April 6, 2006 12:08 PM
Yeah. . .unfortunately there's only :in and it takes an innumerable:
Posted by: Greg at April 6, 2006 12:14 PM


