fmin() Function

The fmin() function returns the smaller of two numeric values. It ensures that if one of the arguments is not a number (NaN), the other valid number is returned. This behavior helps in obtaining a reliable minimum even when dealing with floating-point exceptional cases.


Syntax of fmin()

</>
Copy
double fmin(double x, double y);
float  fminf(float x, float y);
long double fminl(long double x, long double y);

Parameters

ParameterDescription
xFirst numeric value to compare.
ySecond numeric value to compare.

It is worth noting that if one of the arguments is a NaN, fmin() returns the other value. This provides a way to gracefully handle cases where invalid numeric data might be encountered.


Examples for fmin()

Example 1: Finding the Minimum of Two Regular Double Values

This example demonstrates how to use fmin() to compare two double values and print the smaller one.

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    double a = 5.2;
    double b = 3.7;
    
    // Determine the minimum of a and b using fmin()
    double minimum = fmin(a, b);
    
    printf("The minimum value is: %.2f\n", minimum);
    return 0;
}

Explanation:

  1. Two double variables a and b are initialized with the values 5.2 and 3.7 respectively.
  2. The fmin() function compares these values and returns the smaller one, which is stored in the variable minimum.
  3. The result is printed to the console using printf().

Output:

The minimum value is: 3.70

Example 2: Handling NaN Values in Comparison

This example demonstrates the behavior of fmin() when one of the operands is a NaN value.

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    double validValue = 4.5;
    double notANumber = NAN;
    
    // fmin() returns the valid number when one argument is NaN
    double minimum = fmin(validValue, notANumber);
    
    printf("The minimum value when comparing a valid number and NaN is: %.2f\n", minimum);
    return 0;
}

Explanation:

  1. A double variable validValue is initialized with a valid numeric value 4.5, while notANumber is set to NAN.
  2. The fmin() function compares validValue with notANumber and returns validValue since it is the valid number.
  3. The result is printed to the console using printf(), demonstrating that fmin() correctly handles NaN values.

Output:

The minimum value when comparing a valid number and NaN is: 4.50