Summary: | Floating point comparison failure | ||
---|---|---|---|
Product: | gcc | Reporter: | Ian Macky <ian> |
Component: | c | Assignee: | Not yet assigned to anyone <unassigned> |
Status: | RESOLVED DUPLICATE | ||
Severity: | normal | CC: | 166255, 36876, adam, AlekM, anoullez, benoit.sibaud, bernert, birger.b, brad_atcheson, brooks, cognot, csk, CycleTimeChart, debian-gcc, denis.nagorny, deshpand, doko, dsell, dyang, eda-qa, fang, gbburkhardt, gcc-bugs, gcc-erikd, gcczilla1, Graham.Murphy, green, gsinai, gtalbot, have, hjl.tools, ian, ich, ismail, jmurray, konstantin, lani, macracan, mbrudka, mehta, neff.kevin, nicos, nikos42, nouiz, npr1, olcios, P.Schaffnit, paul_blankenbaker, pepalogik, petr.savicky, piaget, pr2345, preciseflight, purnnam1, roebel, rohit.x.tripathi, rozenman, sk2alexa, sliwa, sunjoong, themis_hv, tjf, tterribe, tydeman, u.strempel, vincent-gcc, whaley, wirawan0, xiaoyi_wu, ywei |
Priority: | P3 | ||
Version: | 4.5.0 | ||
Target Milestone: | --- | ||
Host: | Target: | ||
Build: | Known to work: | ||
Known to fail: | Last reconfirmed: |
Description
Ian Macky
2010-09-16 16:57:58 UTC
pr323? As a general rule: never compare floating points for equality, use abs(a-b)<epsilon. As an even more general rule, remember to always specify your target: in this case, for example, I can't reproduce at all the behavior on x86_64 -m64, only with -m32. *** This bug has been marked as a duplicate of 323 *** *** This bug has been marked as a duplicate of 323 *** i?86 is a FLT_EVAL_METHOD 2 target, so for strict C compliance all floating operations and constants are supposed to be evaluated in the precision of long double. The assignment of the constant to a double var or explicit cast to double cause rounding to happen, so your testcase is evaluated as: int main() { double z = 3.14159265358979323846L; puts((long double) z == 3.14159265358979323846L ? "==" : "!="); return 0; } and of course (double) 3.14159265358979323846L != 3.14159265358979323846L. You can use -fexcess-precision=fast (the default unless -std=c99/-std=c89 is requested) for the old behavior, or you can add explicit cast, z == (double) M_PI, or (as usually a good idea) avoid floating point equality/non-equality comparisons, instead check whether difference is smaller than some epsilon. Thanks Jakub. Subject: Re: Floating point comparison failure Thanks everyone. I usually do fuzzy floating-point comparison, except in certain special circumstances. I will switch to using double constants; I'm trying for a code that is maximally portable, so having to worry about what exact compiler switches to use is anathema. And might I add: you people are super-fast! I'm very impressed. |