3

I write this code and run in .net framework 4.6.1 and .net core 2.2, Why result is different ? Thanks.

class Program
{
    static void Main(string[] args)
    {
        float i = 1F;
        float j = 0.1F;

        Console.WriteLine(i - j * 10);

        Console.ReadKey();
    }
}

I expect the output of both platform to be -1.490116E-08, but .net core output is 0.

  • Why would you expect output from two different platforms to be the same? – Sweeper Apr 12 '19 at 07:27
  • Unfortunately, one of the issues with floating point accuracy is that it depends on so many factors. Both the nearly-zero result and the zero are both within the tolerances of what should be acceptable. – Lasse V. Karlsen Apr 12 '19 at 07:28
  • 1
    Bear in mind that expecting it to always return a specific value that isn't zero is just as bad as expecting it to return exactly zero, there's no difference here. You still can't expect it to do that. – Lasse V. Karlsen Apr 12 '19 at 07:28
  • Also, try formatting the value, using the `"R"` format, this should use the roundtrip format and might give you something other than 0. – Lasse V. Karlsen Apr 12 '19 at 07:30
  • Couple of notes: they are producing different float values, so it's not just the formatting. (Core bytes are 0 0 0 0, standard are 0 0 128 178.) And the bytecode produced is the same on both, so it's not something like the calculation being compiled out and replaced with a constant 0. – Rawling Apr 12 '19 at 07:40
  • Interesting! I would expect that .NET Core would be consistent with .NET Framework, at least for things so basic as adding numbers. – Theodor Zoulias Apr 12 '19 at 08:20
  • @TheodorZoulias - bear in mind that depending on the mood of the JIT compiler, otherwise identical code just on the *framework* can produce inconsistent results here, depending on whether it can keep the floating point number in a register (keeping 80-bit representation) or has to spill to a variable (32-bit or 64-bit representation). – Damien_The_Unbeliever Apr 12 '19 at 09:47
  • @Damien_The_Unbeliever this is even worse! So the .NET Framework is not even consistent with the .NET Framework! – Theodor Zoulias Apr 12 '19 at 09:50

0 Answers0