Jump to content
Sign in to follow this  
dormky

How do I assert a single ?

Recommended Posts

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

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

Ended up landing on this, works fine for my purpose :

procedure AssertFloat(const value, should: Extended);
begin
  Assert(Abs(value - should) < 0.00001);
end;

 

  • Sad 1

Share this post


Link to post

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 by dummzeuch

Share this post


Link to post
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
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 :classic_biggrin: 

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×