Can I get Java to throw an exception when comparing between floats when one of them turns out to be NaN?

I spent about 2 hours tracking errors today, and I would find it to be much faster if java throws an exception when comparing NaN with float. It would be nice if I could protect myself from this in the future. Any help is appreciated.

+5
source share
2 answers

A reference to the JVM instruction set specifically prohibits bytecodes that do math with floating point, throwing exceptions and rigidly determines how they should work when the NaN operand. If there is a way to do this, it will either require you to explicitly throw exceptions from NaN, or to use a special compiler to insert these checks for you.

One option that may be useful is to write a function like this:

public static float check(float value) {
    if (Float.isNaN(value))
        throw new ArithmeticException("NaN");
    return value;
}

With this, you can write code for this:

float f = check(myOtherFloat / yetAnotherFloat);

Then this will happen and throw an error. Ideally, with a short function name, this would not be too intrusive.

W

+5
source

float double , NaN false. NaN, , , , 0/0. , 0 , . .

public static double div(double a, double b) {
    if(b == 0) throw new IllegalArguementException();
    return a / b;
}

, 0 , ,

double d = a / (b + 1e-9);

NaN , b >= 0. a == 0, d == 0. .

+2

All Articles