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

Viewed 16343

Also "NaN".to_f returns 0 instead of NaN.

5 Answers

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
Related