double precision and boost unittest?

S

saneman

I have a function that returns a double:

double d1 = compute(a,b,c);

when I do:

std::cout << d1 << std::endl;

I get:

0.125

but when I do:

BOOST_CHECK_EQUAL(d1, 0.125);

I get:

[0.12499999999999999 != 0.125]
failed!


Does unittesting in boost use a special precision?
 
J

James Kanze

BOOST_CHECK_EQUAL(d1, 0.125);
I get:
[0.12499999999999999 != 0.125]
failed!
It is not always possible to compare floating point values for
equality.

Of course it is. It may not always be what is wanted, but it's
certainly possible.

What's not always (reasonably) possible is to specify an exact
floating point value as a literal. There is no floating point
value (at least on most machines) which is equal to 1.43, for
example. (Formally, it's always possible: if we suppose IEEE,
given any precise floating point value, there exists a literal
with no more than 17 digits precision that, when converted to
double, will result in that value; with no more than 53 digits,
you can always specify the value exactly. In practice, however,
that fact is really not very useful.)

One thing that does strike me here: the literal value he gives
IS one that can be represented exactly in a floating point (at
least, on all of the implementations I know). Is this simply by
chance, or not. And if not, maybe he should be testing for the
exact value (and there is an error in his function which causes
the results to be off in the low order bit or bits). Without
knowing what his function is supposed to do, we can't tell.
Use BOOST_CHECK_CLOSE instead:

Note that for most mathematical functions, there is only one
correct result. Checking for equality when testing the function
is the only correct thing to do. Something like
BOOST_CHECK_CLOSE is only applicable to relatively high level,
application code, where limited precision is acceptable. (Note
that you do have to be careful with the literal values in this
case. If the comparison for equality fails, it could be an
error in your code, but it could also be an error in the
compiler routine which converted the literal to an actual
floating point value. (The value you gave for the literal could
also be wrong; the correct value generally will depend on the
floating point representation being used. C99 introduced binary
floating point literals, precisely to avoid this problem, but
they don't seem to be widely implemented, and as far as I know,
haven't be adopted into C++.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top