Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple calculation, different results in c# and delphi

Tags:

c#

delphi

The question is, why do these code snippets give different results?

private void InitializeOther()
{
  double d1, d2, d3;
  int i1;

  d1 = 4.271343859532459e+18;
  d2 = 4621333065.0;
  i1 = 5;

  d3 = (i1 * d1) - Utils.Sqr(d2);
  MessageBox.Show(d3.ToString());
}

and

procedure TForm1.InitializeOther;
var d1, d2, d3 : Double;
    i1 : Integer;
begin
    d1:=4.271343859532459e+18;
    d2:=4621333065.0;
    i1:=5;

    d3:=i1*d1-Sqr(d2);
    ShowMessage(FloatToStr(d3));
end;

The Delphi code gives me 816, while the c# code gives me 0. Using a calculator, I get 775. Can anybody please give me a detailed explanation?

Many thanks!

like image 744
Shunyata Kharg Avatar asked Apr 29 '09 15:04

Shunyata Kharg


2 Answers

Delphi stores intermediate values as Extended (an 80-bit floating point type). This expression is Extended:

i1*d1-Sqr(d2);

The same may not be true of C# (I don't know). The extra precision could be making a difference.

like image 99
dan-gph Avatar answered Nov 11 '22 13:11

dan-gph


Note that you're at the limits of the precision of the Double data type here, which means that calculations here won't be accurate.

Example:

d1 = 4.271343859532459e+18

which can be said to be the same as:

d1 = 4271343859532459000

and so:

d1 * i1 = 21356719297662295000

in reality, the value in .NET will be more like this:

2.1356719297662296E+19

Note the rounding there. Hence, at this level, you're not getting the right answers.

like image 11
Lasse V. Karlsen Avatar answered Nov 11 '22 14:11

Lasse V. Karlsen