R
Raphael Clancy
I was playing around with the basic math functions, and I had some
questions about the way Ruby handles operations with 0 and 0.0.
first we have:
$ ruby -v
ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux]
$ irb
irb(main):001:0> 0/0
ZeroDivisionError: divided by 0
from (irb):1:in `/'
from (irb):1
This is OK, it lets us know that we made a mistake somewhere, but when
we try 0.0/0.0 we get:
irb(main):002:0> 0.0/0.0
=> NaN
Mathematically, this is preferable to division error, but, maybe not
from a programming standpoint? The question here is why should these two
events generate different results?
Now, if we try something like 4.0/0.0 we get, what I would consider,
really weird behavior:
irb(main):003:0> 4.0/0.0
=> Infinity
It is true that as x approaches 0 the limit of 1/x goes to infinity, but
this is not the same as 1/0 = infinity. In this case why would infinity
be preferable to the simpler result, NaN? At first I thought this might
be a precision error, that is the parser is saying that 0.0 is not
really 0, just very close. But, if that was the case then 0.0/0.0 would
be 1 instead of NaN.
Thanks!
questions about the way Ruby handles operations with 0 and 0.0.
first we have:
$ ruby -v
ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux]
$ irb
irb(main):001:0> 0/0
ZeroDivisionError: divided by 0
from (irb):1:in `/'
from (irb):1
This is OK, it lets us know that we made a mistake somewhere, but when
we try 0.0/0.0 we get:
irb(main):002:0> 0.0/0.0
=> NaN
Mathematically, this is preferable to division error, but, maybe not
from a programming standpoint? The question here is why should these two
events generate different results?
Now, if we try something like 4.0/0.0 we get, what I would consider,
really weird behavior:
irb(main):003:0> 4.0/0.0
=> Infinity
It is true that as x approaches 0 the limit of 1/x goes to infinity, but
this is not the same as 1/0 = infinity. In this case why would infinity
be preferable to the simpler result, NaN? At first I thought this might
be a precision error, that is the parser is saying that 0.0 is not
really 0, just very close. But, if that was the case then 0.0/0.0 would
be 1 instead of NaN.
Thanks!