Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in double primitive precision between Java & C#

This does not answer the question.

I ran the same exact code in Java & C# and it gave two differents results.

Why? As the doubles in both languages have the exact same specifications :

double is a type that represents 64-bit IEEE 754 floating-point number in Java

double is a type that represents 64-bit double-precision number in IEEE 754 format in C#.


Java

double a = Math.pow(Math.sin(3), 2);
double b = Math.pow(Math.cos(3), 2);
System.out.println(a);   // 0.01991485667481699
System.out.println(b);   // 0.9800851433251829
System.out.println(a+b); // 0.9999999999999999

C#

double a = Math.Pow(Math.Sin(3), 2);
double b = Math.Pow(Math.Cos(3), 2);
Console.WriteLine(a);   // 0.019914856674817
Console.WriteLine(b);   // 0.980085143325183
Console.WriteLine(a+b); // 1
like image 622
Yassin Hajaj Avatar asked Aug 13 '26 20:08

Yassin Hajaj


1 Answers

It's just the precision that C# is using with the writeLine method. See https://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#GFormatString where it specifies that the G format specifier gives 15-digit precision.

If you write:

Console.WriteLine(a.ToString("R"));

it prints 0.019914856674816989.

like image 191
M A Avatar answered Aug 16 '26 11:08

M A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!