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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With