Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between double comparisons in gtest (C++) and nunit (C#)

I have done porting of a c++ project with gtest tests to a c# project having an nunit test. Now I encounter problems with floating point precision.

in the nunit test I have being not ok (red)

Assert.AreEqual(0.7, 7 * 0.1); 

in the gtest test I have:

ASSERT_DOUBLE_EQ(0.7, 7 * 0.1);

which is ok (green)

The question now is WHY???

like image 806
schoetbi Avatar asked Aug 25 '10 10:08

schoetbi


3 Answers

Google Test's ASSERT_DOUBLE_EQ() verifies that the actual value is within 4 ULPs of the expected one (see more info at https://github.com/google/googletest/blob/main/docs/advanced.md#floating-point-comparison). Nunit is probably performing exact comparison.

like image 92
VladLosev Avatar answered Oct 31 '22 21:10

VladLosev


Alternatively you can add a third parameter, which is the maximum difference between the two values, as you can read here.

public static void AreEqual (
    double expected,
    double actual,
    double delta
)

Verifies that two specified doubles are equal, or within the specified accuracy of each other. The assertion fails if they are not within the specified accuracy of each other.

like image 23
Exa Avatar answered Oct 31 '22 22:10

Exa


never-ever compare floating point numbers for equality! decimal fractional numbers (like 0.1) can't be represented into ieee floats without small precision lost. what may look like 0.7 may be 0.6999999 or something else indeed. they are different numbers then. You should use epsilon technique: consider a == b if abs(a - b) <= epsilon , where epsilon is very small constant number.

read this and many others^

http://docs.sun.com/source/806-3568/ncg_goldberg.html

What's wrong with using == to compare floats in Java?

like image 1
Andrey Avatar answered Oct 31 '22 20:10

Andrey