This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Bizarre output.
- From: corey taylor <corey dot taylor at gmail dot com>
- To: Srinath M <msrinath80 at yahoo dot com>, gcc-help at gcc dot gnu dot org
- Date: Tue, 29 Mar 2005 16:19:49 -0600
- Subject: Re: Bizarre output.
- References: <fc.3b9aca006b2d42243b9aca0024422d6b.428315a@reflex.at> <4249D2EA.4080500@reflex.at>
- Reply-to: corey taylor <corey dot taylor at gmail dot com>
This is one method of fuzzy floating point equates using a
magnitude-based epsilon.
const double fuzzyEpsilon = 0.000001;
/**
Computes an appropriate epsilon for comparing a and b.
*/
inline double eps(double a, double b) {
// For a and b to be nearly equal, they must have nearly
// the same magnitude. This means that we can ignore b
// since it either has the same magnitude or the comparison
// will fail anyway.
(void)b;
const double aa = abs(a) + 1;
if (aa == inf()) {
return fuzzyEpsilon;
} else {
return fuzzyEpsilon * aa;
}
}
inline bool fuzzyEq(double a, double b) {
return (a == b) || (abs(a - b) <= eps(a, b));
}
corey
On Wed, 30 Mar 2005 00:12:58 +0200, Antonio Coralles
<noche.suapie@reflex.at> wrote:
> Srinath M wrote:
>
> > Can someone tell me why the text, "I see it" is not displayed when this
> > program is run?
> >
> > #include <stdio.h>
> >
> >
> > int main(void)
> > {
> > float a, b;
> >
> >
> > double d;
> >
> >
> > a = 0.;
> >
> >
> > b = 1.;
> >
> >
> > for (d = 0.0; d < 0.011; d = d + 0.001)
> > {
> > printf("d = %f\n",d);
> >
> >
> > if (d == 0.009)
> > {
> > printf ("I see it\n");
> > }
> > }
> > return 0;
> > }
> >
> Well, in my opinion you should normally not use "==" in conection with
> float or double, because floating-point arithmetic is not exact (not
> only with gcc). Besides 0.001 has not an exact representation as
> floating point number ... Try
> ...
> if(d > 0.008999 && d < 0.009001)
> printf(...);
> ...
> antonio
>
>