Delphi 5 Strange result when sum double variables

1k views Asked by At

In Delphi 5 i have Strange problem when sum two values ​​of type double and one positive and the other negative same values .

for Example

dbv = 50071763.721
crv = -50071763.721

the result should 0 when sum two values but i got result some thing like 0.0000000074505805969

i did the sum in excel i got 0 result .

4

There are 4 answers

1
Sayat Ertüfenk On

Try to round the result for example

uses Math;

function fnSumValue(): Double;
var
  dbv: Double;
  crv: Double;
begin
  dbv := 50071763.721;
  crv := -50071763.721;
  Result := Math.RoundTo(Abs(dbv) - Abs(crv), -6);
end;
1
Ghigo On

This is due to how floating point numbers are represented.

Your best chance is to define a precision you need, let's say 0.001.

Multiply dbv and crv by 1000 (1/1000=0.001) and round to integer. Now do your sum. Divide back by 1000. Here's your result with needed precision.

result := (round(dbv*1000)+round(crv*1000))/1000;
2
David Heffernan On

What you are claiming is false. For an IEEE754 compliant unit, which is what performs the calculation,

x + (-x) = 0 

for all x other than NaN and Inf.

You have two values, both of which are not equal to the values in the question. We can be sure of that since neither value is representable as binary floating point values. So, clearly you have rounded to three decimal places for presentation, but the underlying numbers are not what appear in the question. And clearly your two values have different absolute value.

Required reading on this topic: What Every Computer Scientist Should Know About Floating-Point Arithmetic

2
J... On
program TestXPlusMinusX;

{$APPTYPE CONSOLE}

uses
  SysUtils;

var dbv, crv : double;

begin
  dbv := 50071763.721;
  crv := -50071763.721;
  if (dbv + crv) = 0 then WriteLn('Sum is Zero');
  WriteLn(dbv + crv);
end.

This gives zero, as David noted. Since you haven't shown us your actual code, we can say nothing other than what you have told us is not what you have done.