tags:

views:

72

answers:

2

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

+3  A: 

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...

apirogov
Fair enough, I just think semantically that 'Not a Number' is a Number is a bit weird...
brad
@brad: well, I agree, the name for that state is not well chosen... :)
apirogov
+3  A: 

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

Nikolaus Gradwohl