Implicit conversion / promotion of float or double in expressions between C # and Java

If I have the following expression:

byte A = 69; int B = 123; long C = 3210; float D = 4.9f; double E = 11.11; double X = (B * 100) + 338.1 - (E / B) / C; double X1 = (B * 100) + (A * D) - (E / B) / C; // JAVA - lost precision System.out.println(X); // 12638.099971861307 System.out.println(X1); // 12638.099581236307 // C# - almost the same Console.WriteLine(X); // 12638.0999718613 Console.WriteLine(X1) // 12638.0999784417 

I noticed that Java is losing precision from X, where 338.1 is an implicit double, and C # is almost gone. I do not understand why, because 338.1 is equal to the float and doubled. After the point there is only one digit.

+7
java c #
source share
2 answers

In Java (B * 100) + (A * D) will be a float; and it will be the float closest to 12638.1. However, 12638 requires 14 digits for binary expression, including the initial 1; which leaves 10 digits of a character to express the fractional part. This way you get the closest number of 1024's to 0.1 - i.e. 102/1024. This turns out to be 0.099609375 - so the float has a rounding error of 0.000390625.

It seems that the difference between X and X1 is what you get in your Java program.

I am afraid that I am not an expert in C #, so I can not tell you why C # is different.

+1
source share

This is due to the interpretation of your expression by compilers. Since you did not specify any conversions of the intermediate type, the compiler performs A * D as a conversion of the first type, and then multiplying instead of the inverse of what you expect. This may seem like a strange result, but it is a way for the compiler to give you a more accurate result without having to specify tedious type conversions.

Java cannot handle this for you, so (B * 100) + (A * D) is a multiplication of int and a float , which leads to a float . This can be modeled in C # as follows:

 double X2 = (float)((B * 100) + (A * D)) - (E / B) / C; Console.WriteLine("X2: {0}", X2); 

This is one of the advantages (or perhaps some of the benefits that they may say) of a high-level compiler.

0
source share

All Articles