Table of Contents

When working with floating-point numbers in Arduino, there may be cases where a calculation results in an invalid number, known as NaN (Not a Number). The isnan() function is used to check whether a floating-point value is NaN. This can be useful in applications involving mathematical computations, sensors, or user inputs.

What is NaN?

NaN stands for Not a Number. It represents undefined or unrepresentable values in floating-point arithmetic. Common situations that produce NaN include:

  • Dividing zero by zero (0.0 / 0.0)
  • Taking the square root of a negative number (sqrt(-1), unless using complex numbers)
  • Performing operations on uninitialized float variables

Syntax

bool isnan(float x);
  • x: The floating-point number to check.
  • Returns: true if the value is NaN, otherwise false.

Example 1: Detecting NaN Values

This example demonstrates how isnan() can be used to check for NaN values.

void setup() {
    Serial.begin(9600);

    float num1 = 0.0 / 0.0; // Produces NaN
    float num2 = sqrt(-1);  // Produces NaN
    float num3 = 10.5;      // Valid number

    if (isnan(num1)) {
        Serial.println("num1 is NaN");
    } else {
        Serial.println("num1 is a valid number");
    }

    if (isnan(num2)) {
        Serial.println("num2 is NaN");
    } else {
        Serial.println("num2 is a valid number");
    }

    if (isnan(num3)) {
        Serial.println("num3 is NaN");
    } else {
        Serial.println("num3 is a valid number");
    }
}

void loop() {
    // Nothing to do here
}

Expected Output:

num1 is NaN
num2 is NaN
num3 is a valid number

Example 2: Checking Uninitialized Float Variables

If a float variable is declared without initialization, it contains random memory data. Checking such a variable with isnan() may not always return true, since it might contain any valid floating-point value.

void setup() {
    Serial.begin(9600);

    float num; // Uninitialized variable

    if (isnan(num)) {
        Serial.println("num is NaN");
    } else {
        Serial.println("num is a valid number (but uninitialized)");
        Serial.print("Value of num: ");
        Serial.println(num);
    }
}

void loop() {
    // Nothing to do here
}

Possible Output:

num is a valid number (but uninitialized)
Value of num: 2.345678e-38  (Random value)

Example 3: Explicitly Setting NaN

If you want to ensure a variable starts as NaN, you can explicitly assign it:

float num = NAN;
if (isnan(num)) {
    Serial.println("num is explicitly set to NaN");
}

Conclusion

The isnan() function is a useful tool for detecting invalid floating-point values in Arduino projects. By properly handling NaN values, you can prevent unexpected behavior in calculations, sensor readings, and data processing tasks. Understanding when NaN occurs and how to detect it helps ensure robustness in embedded systems.

Categorized in:

Arduino Language,