Reputation: 3429
I have a problem, im doing some personal research into how this works http://www.codeproject.com/Articles/17480/Optimizing-integer-divisions-with-Multiply-Shift-i but i did not get far until i got stumped, so the code atm is supposed to return roughly 100% error
double sum = 0, div = 3;
DateTime t1 = DateTime.Now;
List<double> l1 = new List<double>();
for (int a = 0; a < 10000000; a++)
{
sum = a / div;
l1.Add(sum);
}
Console.WriteLine("Milisecond: " + DateTime.Now.Subtract(t1).TotalMilliseconds);
t1 = DateTime.Now;
List<double> l2 = new List<double>();
for (int a = 0; a < 10000000; a++)
{
sum = a * div;
l2.Add(sum);
}
Console.WriteLine("Milisecond: " + DateTime.Now.Subtract(t1).TotalMilliseconds);
int c=0;
int err = 0;
for (int a = 0; a < (l1.Count < l2.Count ? l1.Count : l2.Count); a++)
{
c++;
err += l1[a] != l2[a] ? 1:0;
}
Console.WriteLine("Error: " + 100*(err / c) + "%");
but that last line returns 0 apparently 9999999 / 10000000 = 0
any ideas to how i can work around the problem? my best guess is that its a float problem. (but now i know its a doh error on my part)
Upvotes: 0
Views: 718
Reputation: 14532
The variables of the operation are declared as int and therefore the operation is done on integers and the result is only then converted to double.
To get the double result, you could do:
dRes = (double)x / y;
By the way, there is a better way to test the running time of code:
Stopwatch sw = Stopwatch.StartNew();
// ... Some code
sw.Stop();
Console.WriteLine(sw.Elapsed);
Upvotes: 8
Reputation: 54917
It's not a float
problem; it's an int
problem. You need to cast err
to double
before dividing it.
Console.WriteLine("Error: " + 100 * ((double)err / c) + "%");
Upvotes: 4