Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force 0.0/0.0 to return zero instead of NaN in MIPSPro C compiler?

Tags:

c

nan

As the question states, I am using the MIPSPRo C compiler, and I have an operation that will return NaN for some data sets where both the numerator and denom are zero. How do I keep this from happening?

like image 780
Derek Avatar asked Apr 01 '10 20:04

Derek


People also ask

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 to check if a number 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.

What is the value of NaN in C?

An expression representing positive infinity. It is equal to the value produced by mathematical operations like 1.0 / 0.0 .


1 Answers

On SGI systems with the MIPSPro compiler, you can set the handling of various floating point exceptions with great precision using the facilities in sigfpe.h. As it happens, the division of zero by zero is one such case:

#include <stdio.h>
#include <sigfpe.h>

int main (void) {
    float x = 0.0f;
    (void) printf("default %f / %f = %f\n", x, x, (x / x));
    invalidop_results_[_ZERO_DIV_ZERO] = _ZERO;
    handle_sigfpes(_ON, _EN_INVALID, 0, 0, 0);
    (void) printf("handled %f / %f = %f\n", x, x, (x / x));
    return 0;
}

In use:


arkku@seven:~/test$ cc -version
MIPSpro Compilers: Version 7.3.1.3m
arkku@seven:~/test$ cc -o sigfpe sigfpe.c -lfpe
arkku@seven:~/test$ ./sigfpe
default 0.000000 / 0.000000 = nan0x7ffffe00
handled 0.000000 / 0.000000 = 0.000000

As you can see, setting the _ZERO_DIV_ZERO result changes the outcome of the same division. Likewise you can handle regular division by zero (e.g. if you don't want infinity as the result).

Of course, none of this is standard; it would be more portable to check for NaN after each division and even better to check for zeros before. C99 offers some control over the floating point environment in fenv.h, but I don't think anything suitable for this is available. In any case my old MIPSPro doesn't support C99.

like image 153
Arkku Avatar answered Sep 18 '22 17:09

Arkku