Delphi wrong double precision calculation

Felipe

I am having a problem calculating a simple arithmetic equation using double precision variables.

I have a component that has a property Value which is of double precision, and I am setting this property to 100.

Then I am doing a simple subtraction to check if this value is really 100:

var
check: double;
begin
  check:= 100 - MyComponent.Value
  showmessage(floattostr(check));
end;

The problem is that I don't get zero, I get -1.4210854715202E-14, which is a problem because I the program checks if this result is exactly zero

any idea how to solve it?

David Heffernan

Although you claim otherwise, the value returned by MyComponent.Value is clearly not exactly equal to 100. If it was, then 100 - MyComponent.Value would be exactly equal to 0. We can say that because 100 is exactly representable in binary floating point.

It's easy enough to see that 100.0 - 100.0 = 0.0.

var
  x, y: Double;
....
x := 100.0;
y := 100.0;
Assert(x-y=0.0);

You will find, in your scenario, that

MyComponent.Value = 100.0

evaluates as False.

In general, it can always be a dangerous thing to try to compare floating point values exactly. Particularly if the values are the result of arithmetic operations, then the inherent imprecision of floating point operations will mean that exact comparison will often not give the results that you expect.

I hypothesise that MyComponent.Value actually performs arithmetic rather than, as you claim, returning 100.0.

Sometimes the best way to check for equality with floating point values is to check for approximate equality. For example, abs(x-y)<tol where tol is some small number. The difficulty with that is that it can be hard to come up with a robust choice of tol.

Exactly how you should implement this test is hard to say without knowing more detail.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related