0

I've converted some Matlab code to C#. The problem I have is that the result of the operations must be the same.

Matlab calculates 0.1 + 0.2 = 0.3, while C# = 0.30000000000000004 (https://0.30000000000000004.com/)

Calculation 1 - The same result in C# and Matlab :972,5635799999999

double test1 = 0.016209393 * 60000;
// 972,5635799999999

Calculation 2 - different in C# and Matlab: 2397,1369799999998 in C# and 2397.13698 in Matlab

double test2 = 0.039952283 * 60000;
// 2397,1369799999998

If i use decimal in C# it is calculated to be the same as in Matlab, 2397.13698

decimal test3 = 0.039952283m * 60000;
// 2397.13698

The problem is that I can't use decimal for all calculations, as calculation 1 using decimal would return 972,56358 in C#, while it should be 972,5635799999999 as in Matlab.

How can I make sure I can get the same results from C# and Matlab? Would it be ok to find the base of the fractions and use double or decimal accordingly?

Håkon Rossebø
  • 305
  • 1
  • 6
  • 5
    My recommendation would be to choose a common number of decimal points, and format the outputs to that number of decimal points. Then you should have mostly the same results. As shown on the link you provided, formatting a specific way can lead to the same results: Matlab: `sprintf('%.17f',0.1+0.2) = 0.30000000000000004` C#: `Console.WriteLine("{0:R}", .1 + .2);` = `0.30000000000000004` Really, you just need to be certain the data types you are using are the same, and the formatting for the outputs is the same. – Zaelin Goodman Jan 21 '20 at 14:13
  • 2
    Beware, Matlab print a result rounded to few decimals, `0.1 + 0.2 == 0.3` answers false. In matlab, `format long` prints a bit more decimals, but still not enough to distinguish two very close doubles. – aka.nice Jan 21 '20 at 14:19
  • 1
    Compare it a sufficient number of digits: https://stackoverflow.com/a/35626253/2732801 – Daniel Jan 21 '20 at 15:48
  • 1
    Thanks. Initial tests with 17 digits now give the same results in C# and Matlab. I'll do some more verification and conclude when ready. – Håkon Rossebø Jan 22 '20 at 10:57
  • As mentioned in the comments and in this answer https://stackoverflow.com/a/35626253/346995, Matlab can be confusing by only printing 15 significant digits when using format long. Internally, C# and Matlab use the same numbers, and I have verified that performing multiple aggregated calculations gives the same results. – Håkon Rossebø Jan 24 '20 at 09:19

0 Answers0