Re: comparing doubles for equality
- From: SM Ryan <wyrmwif@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Sun, 31 Dec 2006 07:08:21 -0000
John Smith <JSmith@xxxxxxxx> wrote:
# This code for the comparison of fp types is taken from the C FAQ.
# Any problems using it in a macro?
#
# /* compare 2 doubles for equality */
# #define DBL_ISEQUAL(a,b) (fabs((a)-(b))<=(DBL_EPSILON)*fabs((a)))
#
# Do the same issues involved in comparing 2 fp types for equality
# apply to comparing a float to zero? E.g. is if(x == 0.0)
# considered harmful?
Floats and doubles use a small number of bits for their values,
so exact equality to zero or any other representable value is
meaningful. Two problems are
(1) most machines do not use radix 10 representation; some decimal
values, such as 0.1 can only be approximated. That means if you
write (x==0.1) you're not really testing x against one tenth but
some other value that is close to one tenth. So the test is not
what you think it is.
(2) many computations with reals are iterative approximations to
an unknown value. Because of the precision limits, they often
cannot reach the exact correct value, so you have to accept when
it is close enough.
--
SM Ryan http://www.rawbw.com/~wyrmwif/
So basically, you just trace.
.
- References:
- comparing doubles for equality
- From: John Smith
- comparing doubles for equality
- Prev by Date: Re: comparing doubles for equality
- Next by Date: Re: c / c++ : is it end of era ?
- Previous by thread: Re: comparing doubles for equality
- Next by thread: Good ways to analyze a running c-program?
- Index(es):