I was testing some of mine Ruby 1.9 code when I’ve stumbled across something that is very interesting. I’m hoping that someone can explain why is this happening.
Here is the code:
inf = Float::INFINITY
x = inf - inf
y = 0.0/0.0
puts "X is #{x}"
puts "Y is #{y}"
puts "X and Y are both NaN." if x.nan? && y.nan?
puts "This is all as we expected, but here is the mystery..."
puts "X is not equal to Y." if x == y
puts "Surprisingly not even X is equal to X." if x == x
And this is the output:
X is NaN
Y is NaN
X and Y are both NaN.
This is all as we expected, but here is the mystery...
I have assigned a NaN value in two different ways to two variables and when I’ve tested if they were equal that was not the case. After that I’ve tested if one variable is equal to itself and even that wasn’t true. It’s logical to expect that some value is equal to itself but as we can se, it just isn’t.
I don’t know if this is the right way to test NaN values, but I would really like to know what is behind all of this and is there a reason for a Ruby to behave like this?
Thank you
If we think about it, it seems logical. You get
xby subtracting one infinitely large number from another infinitely large number? What’s the result of that? We don’t know.How can we compare things that we don’t know?
To backup my logic, here’s the source of
Float#==