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
?
double
isn't going to give you the precision you need for that kind of math.
Switch to decimal
and all will be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With