문제

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

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top