Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make the sum of numbers equal to 1

Tags:

c#

double

I work with probabilities and I need to check that the sum of the values is 1. I was writing unit-tests and one of the tests was failing. This is why it was failing:

double[] probabilities = new[] { 0.4, 0.3, 0.2, 0.1 };
double sum = probabilities.Sum();
//On my PC gives sum of 0.99999999999999989

if (sum != 1)
{
    throw new ArgumentException(
        "Sum of the probabilities does not equal to 1. " +
        "Computed value was: " + sum);
}

What can I change to make this true: 0.4 + 0.3 + 0.2 + 0.1 = 1?

like image 382
oleksii Avatar asked Feb 23 '23 10:02

oleksii


1 Answers

double isn't going to give you the precision you need for that kind of math.

Switch to decimal and all will be fine.

like image 103
Justin Niessner Avatar answered Mar 05 '23 05:03

Justin Niessner