Can someone explain to me NaN in Ruby?
I just found a bug in some number manipulations in my program and I'm getting a FloatDomainError (NaN)
So I started logging the number passed in with:
if(metric.is_a?(Numeric))
self.metric = metric
else
LOGGER.warn("metric #{metric} is not a number")
self.metric=0
end
But the number being passed in is NaN
which apparently is_a?(Numeric)
开发者_如何学运维as I don't get my log warning, and it passes metric on to my metric= method, which is where I get my FloatDomainError
Now, correct me if I'm wrong, but doesn't it seem semantically wrong to have an NaN
(Not A Number) be of type Numeric ?? Can someone explain this to me?
BTW using Jruby-1.4.1
I think that making NaN a number makes perfectly sense...
try 0.0 / 0.0 in irb -> the result is NaN (which in this case is infinity)
Infinity is mathematically kind of a number, but still, you can't express it with a datatype... in math you use a special symbol too...
PS: You can use metric.nan? to check it... then it should work as you expect...
IEEE 754 floating point numbers define -INFINITY +INFINITY and NotANumber to make it possible to react to lets say division by zero. you can also calculate with these for eg 2 + INF = INF
NaN isn't a uniqe ruby feature, they are numeric in java, c++, ... too
精彩评论