Monday, December 17, 2007

.Net Math 0.7 + 0.2 = 0.89999999999999991

While developing a multicast simulator for my master thesis I had to sum up the bandwidth distribution of the channels.

So, I did a little routine that while it was parsing the bandwidths it would sum up their probabilities.

After all was summed up … the math did not work out as it was supposed and the overall probability did not sum to 1.

Debugging the app I found that .net was doing a very strange sum of doubles:

Immediate windows:


? TotalProbs
0.7
? prob
0.2
? TotalProbs+prob
0.89999999999999991

Strange enough ?

Am I missing something ?

Is it too late to be doing math ?

Code Block:

using System;

using System.Text;

using System.Globalization;

namespace ConsoleApplication1
{

class Program
{

static void Main(string[] args)

{

string[] tokens = {"0,2", "0,25","0,25","0,2","0,1"};

double TotalProbs = 0; //Count the overall bandwidth probabilities

double prob = 0;

NumberFormatInfo nfi = new NumberFormatInfo();

nfi.NumberDecimalSeparator = ","; //Force the double separator wherever you are.

for (int i = 0; i <>

{

prob = double.Parse(tokens[i], nfi);

TotalProbs += prob;

}

if (TotalProbs !=1)

{

throw new Exception("This should not happen!!!");

}

}

}
}

4 comments:

Tiago Andrade e Silva said...

Also posted in MSDN Forums
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2567268&SiteID=1&mode=1

Sklivvz said...

Hi Tas, you probably forgot some part of your code... see the for loop.

Tiago Andrade e Silva said...

Hi!
You're right. Here is a simpler version:
using System;

using System.Text;

using System.Globalization;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

//The error happens with any of these arrays:
//double[] tokensd = {0.2, 0.25, 0.25, 0.2, 0.1};
//double[] tokensd = { 0.1, 0.1, 0.1, 0.2, 0.1,0.3,0.1 };
double[] tokensd = { 0.65, 0.15, 0.05, 0.05, 0.1 };

double TotalProbs = 0; //Sum the
double prob = 0;

for (int i = 0; i < tokensd.Length; i++)
{
TotalProbs += tokensd[i];
}
if (TotalProbs !=1)
{
throw new Exception("This should not happen!!!");
}
}
}
}

Anonymous said...

Another blog about this issue
http://scrappydog.com/user/CreateUser.aspx?ReturnUrl=/blogs/blog/archive/2006/08/04/9996.aspx