2

I have recently started using googletest to set up some unit-testing and ran into a situation which I don't understand. The test fails but everything looks like it would pass.

I have a small struct similar to this:

struct vec2 { float x, y; }

a function:

vec2 vec2_add_scalar (vec2 v, float scalar) {
    return {v.x + scalar, v.y + scalar};
}

and the test:

TEST (math_test, add_scalar) {
    vec2 v {4.0f, -4.0f};
    float s = 3.14f;

    vec2 r = vec2_add_scalar(v, s);

    EXPECT_EQ (7.14f, r.x);
    EXPECT_EQ (-0.86f, r.y);
}

When running the test this is what I get:

[ RUN      ] vector2_test.add_scalar
vec2_test.cpp: Failure
    Expected: 7.14
To be equal to: r.x
    Which is: 7.14

I don't understand why the test fails, and would appreciate help in figuring out what might make the test fail.

qrikko
  • 2,483
  • 2
  • 22
  • 35
  • strict vs. precise floating point compiler settings perhaps? Does it work with 400f, -400f, and 314f? – Bathsheba May 31 '16 at 07:33
  • Floating-point math requires reading and understanding, there are many pitfalls. One newbie error is to compare floats with equals. You always should compare with an interval, e.g. EXPECT_TRUE(r.x - 7.14f < delta && r.x - 7.14f > -delta). – Erik Alapää May 31 '16 at 07:33
  • "Floating-point math requires reading and understanding, there are many pitfall". Indeed, very good. "You always should compare with an interval", no that's hogwash and eclipsed by your first part of the comment. – Bathsheba May 31 '16 at 07:34
  • @Batsheba. YOU are talking hogwash. You shall not compare floats/doubles with equals, period. – Erik Alapää May 31 '16 at 07:36
  • @ErikAlapää: sadly no time to go into this. But there are plenty of instances where you can compare exactly. – Bathsheba May 31 '16 at 07:38
  • @Batsheba: Can you give anything but trivial examples? – Erik Alapää May 31 '16 at 07:40

2 Answers2

2

As you might read in googletest-AdvancedGuide, it is advised to use ASSERT_FLOAT_EQ/ASSERT_DOUBLE_EQ...

For reason why - please read this SO post: Floating point inaccuracy examples

rold2007
  • 1,297
  • 1
  • 12
  • 25
PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
1

Do not compare floating-point numbers with equality, use an interval. Read up on guidelines for floating-point programming. Here is a start: http://lec.inf.ethz.ch/ifmp/2014/ex_class_materials/week05/Floating_Point_Guidelines%20(EN).pdf

Erik Alapää
  • 2,585
  • 1
  • 14
  • 25