[英]Java Junit4: assertEquals for ArrayList<Double> with single precision expected values
I'm writing a JUnit test for a Java variable that is ArrayList<Double>
. 我正在为ArrayList<Double>
的Java变量编写JUnit测试。 The complication is that my expected values are single precision whereas Java's Double
is double precision. 复杂的是,我的期望值是单精度,而Java的Double
是双精度。 So doing assertEquals(expected_array_list, actual_array_list)
does not pass due to precision errors. 因此assertEquals(expected_array_list, actual_array_list)
由于精度错误assertEquals(expected_array_list, actual_array_list)
执行assertEquals(expected_array_list, actual_array_list)
不会通过。
My work-around is to iterate over all the elements and assertEquals
each pair of doubles, setting the epsilon
value to an appropriate value. 我的变通办法是遍历所有元素,并assertEquals
每一对double都assertEquals
,将epsilon
值设置为适当的值。 Is there a method of setting the epsilon
for the entire ArrayList
, instead of having to decompose it into its elements? 有没有一种方法可以为整个ArrayList
设置epsilon
,而不必将其分解为元素?
JUnit 4.6 and above has a convenience method assertArrayEquals(double[] expected, double[] actual, double delta)
method (with an overloaded variant for a String
message, as per the norm). JUnit 4.6及更高版本具有便捷的方法assertArrayEquals(double[] expected, double[] actual, double delta)
方法(按照规范, String
消息具有重载的变体)。 In Java 8, you could convert those List
s to primitive arrays pretty easily and just use it: 在Java 8中,您可以很容易地将这些List
转换为基本数组,然后使用它:
double delta = 0.05; // or any other reasonable value
double[] expectedArray =
expectedList.stream().mapToDouble(Double::doubleValue).toArray();
double[] actualArray =
actualList.stream().mapToDouble(Double::doubleValue).toArray();
assertArrayEqulas(expectedArray, actualArray, delta);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.