Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does NaN not propagate in C++?

Tags:

c++

nan

NaN propagates through "most" operations as described in NaN - Wikipedia.

I would like to know the operations which NaN does NOT propagate. For example, I'm coding in C++ and found that following code prints 1, which is not NaN.

const double result = std::pow(1, std::numeric_limits<double>::quiet_NaN());
std::cout << result << std::endl;

For std::powfunction, this behavior is described in std::pow - cppreference.com.

Could you share any other examples?

like image 472
Tomoyuki Aota Avatar asked Mar 02 '18 10:03

Tomoyuki Aota


People also ask

How to check if value is NaN in 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.

Why does NaN exist?

Why does NaN exist? NaN is a commonly used term in coding to represent the output of a mathematical expression that isn't a number. It's not 0, it's not infinity, its just not a number that exists. Interestingly, if you run typeof NaN it will equal number — NaN is a number type.


1 Answers

Here's an example demonstrating functions of NaN which return non-NaN. The list is in IEEE 754-2008, 9.2.1 Special values (there are some others functions, but they don't seem to be implemented in C++):

#include <cmath>
#include <limits>
#include <iostream>

int main()
{
    const auto nan=std::numeric_limits<double>::quiet_NaN();
    const auto inf=std::numeric_limits<double>::infinity();
    std::cout << std::hypot(nan,inf) << '\n';
    std::cout << std::hypot(inf,nan) << '\n';
    std::cout << std::pow(nan, 0) << '\n';
    std::cout << std::pow(1,nan) << '\n';
}

The output is:

inf
inf
1
1
like image 123
Ruslan Avatar answered Sep 24 '22 16:09

Ruslan