Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intentionally return NaN

Tags:

c++

nan

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.

like image 227
asimes Avatar asked Dec 07 '12 08:12

asimes


People also ask

How do I return NaN in CPP?

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.

What is the meaning of NaN in c?

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

How to check if a Number is NaN c?

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.

What causes NaN in C?

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.


3 Answers

This should work:

#include <limits>

return std::numeric_limits<double>::quiet_NaN();
like image 61
unwind Avatar answered Oct 06 '22 13:10

unwind


return std::numeric_limits<double>::quiet_NaN();
like image 21
Henrik Avatar answered Oct 06 '22 13:10

Henrik


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.

like image 8
The_Rafi Avatar answered Oct 06 '22 12:10

The_Rafi