Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to produce a NaN float in c?

float f = (float)'a'; if(f < 0){  }    else if(f == 0){  }    else if(f > 0){  }    else{     printf("NaN\n");                                                           }    

f won't be greater/equal/less than 0 if it's a NaN.

But how to produce such a f in the first place?

I tried various ways to produce a NaN,but none work..

like image 820
Je Rog Avatar asked Aug 27 '11 03:08

Je Rog


People also ask

What is NaN in floating-point?

In computing, NaN (/næn/), standing for Not a Number, is a member of a numeric data type that can be interpreted as a value that is undefined or unrepresentable, especially in floating-point arithmetic.

Does NaN exist 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).

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.

How do you test a NaN float?

Checking if a double (or float) 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.


1 Answers

Using floating point numbers, 0.0 / 0.0 isn't a "divide by zero" error; it results in NaN.

This C program prints -nan:

#include <stdio.h>  int main() {     float x = 0.0 / 0.0;     printf("%f\n", x);     return 0; } 

In terms what NaN looks like to the computer, two "invalid" numbers are reserved for "signaling" and "quiet" NaN (similar to the two invalid numbers reserved for positive and negative infinity). The Wikipedia entry has more details about how NaN is represented as an IEE floating point number.

like image 131
Dan Cecile Avatar answered Sep 22 '22 13:09

Dan Cecile