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.
C++ nan() The nan() function in C++ returns a quiet NaN (Not-A-Number) value of type double. The function is defined in <cmath> header file.
NaN is unordered: it is not equal to, greater than, or less than anything, including itself. x == x is false if the value of x is NaN. You can use this to test whether a value is NaN or not, but the recommended way to test for NaN is with the isnan function (see Floating-Point Number Classification Functions).
To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11. So From C++11 next, we can use this function.
NaN, an acronym for Not a Number is an exception that usually occurs in the cases when an expression results in a number that is undefined or can't be represented. It is used for floating-point operations. For example: The square root of negative numbers.
This should work:
#include <limits>
return std::numeric_limits<double>::quiet_NaN();
return std::numeric_limits<double>::quiet_NaN();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With