double roundoff error in calculations

Lawrence254 0 Reputation points
2024-05-10T16:47:06.63+00:00

All of these following code statements should yield the same value, but the second to fourth statement have a second to last digit rounding error in c#. The first statement is correct and fifth to last are correct. Do you know this is happening?

Console.WriteLine(360.0 / 365.2421875);

Console.WriteLine(360.0 + 360.0 / 365.2421875 - 360.0);

Console.WriteLine(360.0 * (365.2421875 + 1.0) / 365.2421875 % 360.0);

Console.WriteLine((360.0 / (365.2421875 / (365.2421875 + 1.0))) % 360.0);

Console.WriteLine((decimal)(360.0m / 365.2421875m));

Console.WriteLine((decimal)(360.0m + 360.0m / 365.2421875m - 360.0m));

Console.WriteLine((decimal)(360.0m * (365.2421875m + 1.0m) / 365.2421875m % 360.0m));

Console.WriteLine((decimal)((360.0m/ (365.2421875m / (365.2421875m + 1.0m))) % 360.0m));

Console.WriteLine(360.0m / 365.2421875m);

Console.WriteLine(360.0m + 360.0m / 365.2421875m - 360.0m);

Console.WriteLine(360.0m * (365.2421875m + 1.0m) / 365.2421875m % 360.0m);

Console.WriteLine((360.0m / (365.2421875m / (365.2421875m + 1.0m))) % 360.0m);

Developer technologies | C#
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 78,006 Reputation points Volunteer Moderator
    2024-05-11T16:00:06.18+00:00

    With the Decimal type, all arithmetic is integer with implied decimal point. So it can accurately do decimal arithmetic. decimal has 28-29 significant digits depending on the number.

    With double, all arithmetic is done in base 2 using floating point math (which can lose precision) and is converted to base 10 on display. This conversion is only approximate because not all base 2 fractions convert to decimal fractions. Double has 15-17 significant digits depending on the number.

    double because it’s a digit plus exponent can represent very large and very small numbers.

    0 comments No comments

  2. Bruce (SqlWork.com) 78,006 Reputation points Volunteer Moderator
    2024-05-12T16:12:59.84+00:00

    your results are expected.

    Not all decimal (base 10) fractions can be accurately converted to double (base 2). Just like 1/3 can not be converted to a decimal fraction, many decimal fractions can not be accurately converted to base 2.

    There is often approximation when a decimal numbers (with fractions) are converted to double (or float) and again when a double is converted to decimal for display.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.