dormky 4 Posted yesterday at 10:45 AM Consider : procedure Test(); var number: single; begin number := 0.96493138416; // Too long for a single precision // Assert(number = 0.96493138416); // Will fail, normal number := RoundTo(number, -3); Assert(number = 0.965); Fails end; Here number is supposed to be a value I'm getting from the data I'm running the test on. Due to binary representation the number will never be exactly correct, however trying to Assert with the value given by the debugger doesn't work either. So how am i meant to assert on floats ? Thanks. Share this post Link to post
Cristian Peța 117 Posted yesterday at 11:14 AM Maybe using SameValue(number, 0.965, 0.001)? Or if you need all the precision the test binary. Share this post Link to post
Anders Melander 2007 Posted yesterday at 11:16 AM Multiply by a 10^"number of decimals", Trunc to convert to integer, Assert on the integer value 1 Share this post Link to post
David Heffernan 2441 Posted yesterday at 11:59 AM It depends a bit on what your goals are. But if you want to test equality then you need to put the expected value into a single. That's hard to do in a compiler because delphi literal syntax doesn't allow to specify the type of a floating point literal. You could declare a typed constant of single type and compare against that. Share this post Link to post
dormky 4 Posted yesterday at 12:36 PM Ended up landing on this, works fine for my purpose : procedure AssertFloat(const value, should: Extended); begin Assert(Abs(value - should) < 0.00001); end; 1 Share this post Link to post
dummzeuch 1644 Posted yesterday at 04:11 PM (edited) What's wrong with Assert(SameValue(Value, Should)) Or, if you want to set the maximum allowed difference yourself Assert(SameValue(Value, Should, MaxDelta)) Edit: @Cristian Peța already suggested that. Edited yesterday at 04:13 PM by dummzeuch Share this post Link to post
David Heffernan 2441 Posted yesterday at 05:03 PM Every time someone calls SameValue a puppy dies 2 1 Share this post Link to post
dummzeuch 1644 Posted 9 hours ago 15 hours ago, David Heffernan said: Every time someone calls SameValue a puppy dies OK, I bite: What's the problem with SameValue? Share this post Link to post
Rollo62 581 Posted 8 hours ago 21 hours ago, Anders Melander said: Multiply by a 10^"number of decimals", Trunc to convert to integer, Assert on the integer value I do the same in many places, even keeping Integers for example by the Factor 10000 stored somewhere in the first place, but then you must ensure that it never happens that there is an unexpected overflow of the Integer. Thats why this solution always leaves me with a bad feeling, when I used it, ... but there's no such thing as a free lunch Share this post Link to post