Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C - float checking for nan

I have a variable float slope that sometimes will have a value of nan when printed out since a division by 0 sometimes happens.

I am trying to do an if-else for when that happens. How can I do that? if (slope == nan) doesn't seem to work.

like image 811
teepusink Avatar asked Aug 12 '10 21:08

teepusink


People also ask

How do I know if my float is NaN?

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.

What makes a float NaN?

NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis.

What is the value 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 do I get NaN in C++?

CPP. Another way to check for NaN is by using “isnan()” function, this function returns true if a number is complex else it returns false. This C library function is present in <cmath> header file.


2 Answers

Two ways, which are more or less equivalent:

if (slope != slope) {
    // handle nan here
}

Or

#include <math.h>
...
if (isnan(slope)) {
    // handle nan here
}

(man isnan will give you more information, or you can read all about it in the C standard)

Alternatively, you could detect that the denominator is zero before you do the divide (or use atan2 if you're just going to end up using atan on the slope instead of doing some other computation).

like image 180
Stephen Canon Avatar answered Oct 18 '22 17:10

Stephen Canon


Nothing is equal to NaN — including NaN itself. So check x != x.

like image 36
Chuck Avatar answered Oct 18 '22 18:10

Chuck