inaccurate modulo function?

  • Thread starter Thread starter Alexander
  • Start date Start date
A

Alexander

I played a little bit with modulo cause I wanted to implement a small
parser for functions as I stumbled over a calculation error. First I
thought the reason might be a type conversion I did before, but see
this small example:

using System;
namespace modulo_test
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("(5%2.2) = {0}\n", 5%2.2);
for (double i=0.1; i<1; i=i+0.1)
{
double calc1 = (5%2.2)-i;
double calc2 = 0.6-i;
Console.WriteLine("(5%2.2)-{0} = {1} \t 0.6-{0} = {2}",
i, calc1, calc2);
}
}
}
}

---------
Output:

(5%2.2) = 0.6

(5%2.2)-0.1 = 0.5 0.6-0.1 = 0.5
(5%2.2)-0.2 = 0.4 0.6-0.2 = 0.4
(5%2.2)-0.3 = 0.3 0.6-0.3 = 0.3
(5%2.2)-0.4 = 0.2 0.6-0.4 = 0.2
(5%2.2)-0.5 = 0.0999999999999996 0.6-0.5 = 0.1
(5%2.2)-0.6 = -3.33066907387547E-16 0.6-0.6 = 0
(5%2.2)-0.7 = -0.1 0.6-0.7 = -0.1
(5%2.2)-0.8 = -0.2 0.6-0.8 = -0.2
(5%2.2)-0.9 = -0.3 0.6-0.9 = -0.3
(5%2.2)-1 = -0.4 0.6-1 = -0.4
 
Alexander,

It's not that the modulo function is inaccurate, but rather the double
type can't accurately represent floating point values. If you need this
kind of precision, then you should use the Decimal type. The following code
will give you what you want:

using System;

namespace modulo_test
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("(5%2.2) = {0}\n", 5 % 2.2m);
for (Decimal i = 0.1m; i < 1; i = i + 0.1m)
{
Decimal calc1 = (5 % 2.2m) - i;
Decimal calc2 = 0.6m - i;
Console.WriteLine("(5%2.2)-{0} = {1} \t 0.6-{0} = {2}",
i, calc1, calc2);
}
}
}
}

Hope this helps.
 
Back
Top