I want to know what makes a float number nan in c++. I am using a large dataset and it is really hard to trace. I want to know the ways of changing a float number to nan to reduce bug possibilities.
I found the code that causes the nan problem. I found that s/m is nan in some cases. But I don't know how to solve it.
float gp(float x){
float e = 2.71828183;
x *= -1;
float s = pow(e,x);
float m = (1 + pow(e,x)) * (1 + pow(e,x));
return s / m;}
A -nan can also be produced by setting all 32 bits of a float variable as 1, as shown below: float nan_val = 0xffffffff; Also, you can compare if a float variable is -nan explicitly by checking if comparison with itself fails. This method of comparison should work for compilers that use IEEE floats.
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.
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).
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.
Taken from wikipedia -> special values -> nan
Looking at you code: infinity times 0 is possible, is it?
0 <= s <= +inf
1 <= m <= +inf
s / m:
I think that's the only thing that makes a NaN.
If you can keep x
between 0 and FLT_MAX
(3.40E+38 in my case), your gp function will not return NaN.
You say in a comment that you only use *
, +
, -
.
[Edit: you've since said that you also use pow
and division, which introduce some extra ways to get NaN. For example if the parameter x
is a large negative value then pow(e,-x)
is infinity, so you can easily end up computing infinity/infinity, which is another NaN]
So, if you have IEEE floating-point then assuming this summary is correct, the only ways you can generate NaN are:
or:
So if you check for and catch infinities, you don't have to worry about NaNs as well. That said, the usual way is to let such values propagate as quiet NaNs, and check at the end.
For C++ implementations using non-IEEE arithmetic, I'm not sure what the rules are when a NaN is permitted. I could look them up in the standard, but then again so could you ;-)
sqrt(-1)
give you NaN, for example. http://www.gnu.org/s/libc/manual/html_node/Infinity-and-NaN.html
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