Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain to me NaN in Ruby?

Tags:

numbers

ruby

nan

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

like image 288
brad Avatar asked Sep 01 '10 14:09

brad


2 Answers

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

like image 98
apirogov Avatar answered Oct 27 '22 08:10

apirogov


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

like image 31
Nikolaus Gradwohl Avatar answered Oct 27 '22 09:10

Nikolaus Gradwohl