4

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?

5
  • try to edit if (sum != 1.0) Nov 11, 2011 at 16:52
  • Another way is to use int. Multiply your probabilities by 100 (0.4 -> 40). Then you can check that sum != 100 Nov 11, 2011 at 16:53
  • @razbakov probability is usually used as a value from [0,1], so I can't use int.
    – oleksii
    Nov 11, 2011 at 16:56
  • 1
    possible duplicate of C# Maths gives wrong results!
    – cHao
    Nov 11, 2011 at 17:01
  • (Note, i'm not sure how the duplicates-marking thing works, but the question linked above is not the question i mistakenly voted as a dupe. If you vote to close, use the link above rather than picking what i picked. :P )
    – cHao
    Nov 11, 2011 at 17:07

3 Answers 3

6

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

Switch to decimal and all will be fine.

2
  • @Henk Holterman - You may not want to, but if you want precise calculations with those numbers, you'll need to. The OP also doesn't make mention of any Unit Testing frameworks. Nov 11, 2011 at 16:56
  • Just checked this, worked for me. Tnx! Will need to rewrite some logic
    – oleksii
    Nov 11, 2011 at 16:57
1

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...

1

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

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.