Double roll for Double less than zero

Double out = otherTypes.someMethod(c, c2);
assertEquals((Double)-1.0D, out);

I get the “Double in assertEquals” error message, is there any way to crack it besides extracting the variable?

Is this a bug in Java or just a very useful feature that will not be fixed?

+3
source share
5 answers

One important note: because of how the floating-point number, you should never compare the two doubled the number (or floating point numbers in general) for direct equity, always compare if their difference is within a certain delta abs(double1 - double2) < delta.

JUnit has a method assertEquals(double expected, double actual, double delta)to do just that. However, you should probably use something like

assertEquals(-1.0d, (double) out, 0.000001d)

in your code.

, , : " ?"

+6

jjnguy's

assertEquals(Double.valueOf(-1.0D), out)

, Double.valueOf , .

+2

-1.0D Double, , , Double.valueOf(-1.0D). Double valueOf, . - , . out.doubleValue(), . , null, , , , .

. , , , , . , , , :

assertTrue(Math.abs(-1.0D-out.doubleValue()) < delta);

JUnit :

assertEquals(-1.0d, out.doubleValue(), delta);

delta, 10E-10, - . , , , , :

double tDelta = delta*(Math.abs(-1.0D)+Math.abs(out.doubleValue()));
assertEquals(-1.0d, out.doubleValue(), tDelta);

If you are comparing very large numbers, you want the resolved delta to be larger, and if you are comparing very small digits, you want the resolved delta to be smaller. But for your case, you know one of your parameters in advance, so you can simply transcode the delta.

+1
source

My suggestion is when you want to check if two doubles match:

assertEquals(Double.doubleToLongBits(-1.0), Double.doubleToLongBits(out));
0
source

This happens through the compiler:

assertEquals(Double.class.cast(-1.0D), out);
0
source

Source: https://habr.com/ru/post/1698559/


All Articles