Intentionally return NaN
Asked Answered
F

4

24

I'm writing a ray tracer and part of the process is firing a ray that may or may not hit an object (geometric object). A number of the equations that describe objects return NaN naturally if no intersection happened (the intersection is imaginary) but not all of the objects return NaN if no intersection happened.

I know that I could force returning sqrt(-1) if no intersection happened, but I was wondering if there is a way to return this in a less expensive way.

Flavin answered 7/12, 2012 at 8:52 Comment(0)
B
32

This should work:

#include <limits>

return std::numeric_limits<double>::quiet_NaN();
Buschi answered 7/12, 2012 at 8:56 Comment(1)
I guess it took me a minute to look up the proper header. :) I'll leave this for now, I think it's marginally better than the accepted answer.Buschi
S
18
return std::numeric_limits<double>::quiet_NaN();
Sholem answered 7/12, 2012 at 8:55 Comment(0)
S
8

I know it's an old question, but with C++11 you have the nan(const char*) family of functions (nan for doubles, nanl for long doubles and nanf for floats). The argument is implementation specific, but passing an empty string (e.g. nan("")) returns a generic NaN value.

Starshaped answered 13/8, 2015 at 17:22 Comment(1)
Here's a reference to the nan function: cplusplus.com/reference/cmath/nan-functionEquip
D
2

The NAN macro from math.h also works.

Deidredeific answered 17/8, 2020 at 17:59 Comment(1)
Should probably use <cmath> instead of <math.h> in C++.Clomb

© 2022 - 2024 — McMap. All rights reserved.