Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java maths - testing for NaN

Tags:

java

math

nan

I would like to have some kind of project-wide fail fast mechanism (maybe a RuntimeException) for any code that causes assignment of NaN.

In my project NaN is never a valid value.

I realise I could add asserts (using isNaN) or other tests throughout but I want to know if there is a more elegant way.

like image 413
Pool Avatar asked Jan 26 '10 15:01

Pool


People also ask

How does Java deal with NaN?

In mathematics, taking the square root of a negative number results in an imaginary number. This case is dealt with by returning NaN in Java. Taking mod of a number with zero, will return the remainder after dividing a value by zero. Hence, NaN is returned.

How do you represent NaN in Java?

In Java, "NaN" stands for "not a number" and signifies that a value is not defined. "NaN" is not an exception error, but a value that is assigned. For example, imaginary numbers like the square root of negative numbers or zero divided by zero will both print "NaN" as the result.

Is NaN a double Java?

Java defines NaN constants of both float and double types as Float. NaN and Double. NaN: “A constant holding a Not-a-Number (NaN) value of type double.

Is NaN a logical error in Java?

NaN means "not a number", and you got it because regular floating-point math doesn't support imaginary numbers. It's a placeholder that means "invalid value", but it's not an error at the language level. Show activity on this post. It's not an error or exception.


Video Answer


1 Answers

Yes, you can use AspectJ (aspect oriented programming) to throw an error whenever a value is set to NaN.

Essentially, you want to intercept whenever a value is set, and perform some other function.

We've done similar things in our codebase ... but I can't give you much help outside of that.

like image 138
Reverend Gonzo Avatar answered Oct 27 '22 19:10

Reverend Gonzo