www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - float equality

reply spir <denis.spir gmail.com> writes:
Hello,

What do you think of this?

unittest {
     assert(-1.1 + 2.2 == 1.1);          // pass
     assert(-1.1 + 2.2 + 3.3 == 4.4);    // pass
     assert(-1.1 + 3.3 + 2.2 == 4.4);    // fail
     assert(-1.1 + 3.3 == 2.2);          // fail
}

There is approxEquals in stdlib, right; but shouldn't builtin "==" be 
consistent anyway?

Denis
-- 
_________________
vita es estrany
spir.wikidot.com
Feb 19 2011
next sibling parent Simon Buerger <krox gmx.net> writes:
On 19.02.2011 13:06, spir wrote:
 Hello,

 What do you think of this?

 unittest {
 assert(-1.1 + 2.2 == 1.1); // pass
 assert(-1.1 + 2.2 + 3.3 == 4.4); // pass
 assert(-1.1 + 3.3 + 2.2 == 4.4); // fail
 assert(-1.1 + 3.3 == 2.2); // fail
 }

 There is approxEquals in stdlib, right; but shouldn't builtin "==" be
 consistent anyway?

 Denis

It is generally a bad idea to use "==" with floats, as most decimals cant be represented exact in binary floating point. That means there is no float for the value "1.1". Though there are exact floats for 0.25, 0.5, 42.125 and so on. The only reason the first two testcases work is, that it is rounded the same way both sides of the "==" but you should not rely on that. Also note, that these calculations are probably done at compile-time, and the compiler is allowed to use a higher precision than at run-time, so you might get different result when you let the user input the numbers. - Krox
Feb 19 2011
prev sibling parent so <so so.so> writes:
On Sat, 19 Feb 2011 14:06:38 +0200, spir <denis.spir gmail.com> wrote:

 Hello,

 What do you think of this?

 unittest {
      assert(-1.1 + 2.2 == 1.1);          // pass
      assert(-1.1 + 2.2 + 3.3 == 4.4);    // pass
      assert(-1.1 + 3.3 + 2.2 == 4.4);    // fail
      assert(-1.1 + 3.3 == 2.2);          // fail
 }

 There is approxEquals in stdlib, right; but shouldn't builtin "==" be  
 consistent anyway?

 Denis

Strange no one mentioned this. Problem is not the floating point format in your example. I can do the same with integral numbers, how? int(5) / int(2) => int(2) or int(3)? And why? Answer depends on the rounding mode, if you don't know the given rounding mode for a (machine interpreted) number system you can't say anything. You know the answer because you know the rule. I can say same for the floating points since i know how they work.
Feb 21 2011