Net6 C#, Linux vs Windows, different floating point calculations?

Omar El Hassani 6 Reputation points
2022-11-21T09:11:23.04+00:00

I am doing floating point calculation with doubles with C# under Net6 (runtime Net 6.0.2) on Windows (Windows Server 2019 Datacenter) and Linux (ubuntu 20.04), and I get different results.

I did this :

double a = 350668.75030235935;  
double b = 5.484834659364377;  
double result = a * (Math.Pow((1 + b / 100), 1.0 / 12.0) - 1);  
byte[] aa = BitConverter.GetBytes(a);  
byte[] bb = BitConverter.GetBytes(b);  
byte[] rr = BitConverter.GetBytes(result);  
  
Console.WriteLine("a * ((1 + b / 100)^(1 / 12) - 1)\n");  
Console.WriteLine("a = " + a.ToString() + " (hexa = " + BitConverter.ToString(aa).Replace("-", "") + ")");  
Console.WriteLine("b = " + b.ToString() + " (hexa = " + BitConverter.ToString(bb).Replace("-", "") + ")");  
Console.WriteLine("result = " + result.ToString() + " (hexa = " + BitConverter.ToString(rr).Replace("-", "") + ")");  

I compile with Windows and Linux with x64 target platform :

262507-image.png

Linux

I run them both with the command line on environments with the same runtime :
262527-image.png

262536-image.png

And as you see, I get different results (I also put the hexadecimal representation so that there's no mistake it's the values, not the way they are converted to string).

This is highly unexpected. I didn't find anything on the subject (except about gcc, but Net6 doesn't use gcc, or does it ?).

Any solution to get the exact same results on both platforms ?

.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,122 questions
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,526 Reputation points
    2022-11-21T19:22:20.007+00:00

    the roslyn compiler (and thus C#) does not implement strict IEEE floating point precision, but rather optimizes for performance. It its not surprising that they don't match when log operations are done. the machines may need to be the exact same hardware and matching versions of Roslyn (as code optimization can change the precision) to get a match. But even this may not work.

    1 person found this answer helpful.