Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare NaN (not a number) in Ruby?

Tags:

ruby

nan

Since Ruby 1.9.3 there is a constant to get the NaN value

Float::NAN
=> NaN

If you need to test if a number is NaN, you can use #nan? on it:

ruby-1.8.7-p352 :008 > (0/0.0).nan? #=> true 
ruby-1.8.7-p352 :009 > (0/1.0).nan? #=> false 

The simplest way is to use 0.0 / 0.0. "NaN".to_f doesn't work, and there's some discussion in this thread about why.


0.0 / 0.0 works for me on ruby 1.8.6.

The thread linked to by Pesto has this function, which should work on platforms where floating-point numbers are implemented according to IEEE 754:

def aNaN
    s, e, m = rand(2), 2047, rand(2**52-1)+1
    [sprintf("%1b%011b%052b", s,e,m)].pack("B*").unpack("G").first
end