开发者

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

开发者 https://www.devze.com 2023-02-10 10:39 出处:网络
I spent about 2 hours tracking down a bug today and I would\'ve found it much quicker had java thrown an exception when comparing NaN with a float.It would be nice if I could开发者_开发问答 protect my

I spent about 2 hours tracking down a bug today and I would've found it much quicker had java thrown an exception when comparing NaN with a float. It would be nice if I could开发者_开发问答 protect myself from this in the future. Any help is appreciated.


The JVM instruction set reference specifically disallows the byte codes that do floating point math from throwing exceptions and rigidly specifies how they should work when NaN is an operand. If there is a way to do this, it will either require you to explicitly throw exceptions on NaN or to use a custom compiler to insert these checks for you.

One option that might be helpful would be 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 to this effect:

float f = check(myOtherFloat / yetAnotherFloat);

This will then do the computation and throw on an error. Ideally with a short function name it won't be too obtrusive.

W


The protection in float or double is to make the result NaN or false. If you want to detect NaN, you are better of preventing the value in the first place e.g 0/0. When you do a division, check for 0 as a divisor and throw an Exception if it is. You can wrap this with a helper method to simplify.

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

If I know the value could be 0 or more only, I often add a bias like

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

This never produces NaN provided b >= 0. If a == 0, d == 0. The bias to use depends on the situation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号