oleksii
oleksii

Reputation: 35925

How do I make the sum of numbers equal to 1

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?

Upvotes: 4

Views: 1567

Answers (3)

Bryan Crosby
Bryan Crosby

Reputation: 6554

decimal has the precision you want. If you need base 10 accuracy, stick with a decimal.

Here is an older, but relevant article on the topic: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Upvotes: 1

Charles Bretana
Charles Bretana

Reputation: 146557

almost all unit test systems have an assert that checks doubles for "closeness" That two values are within some specified tolerance. NUnit Assert.AreEqual, for example, has an overload that takes three doubles, the actualvalue, the expected value, and the delta value, which is the maximum amount that the first two values can differ by for the Assert to pass...

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245479

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

Switch to decimal and all will be fine.

Upvotes: 6

Related Questions