[英]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. 我使用概率,我需要检查值的总和是1.我正在编写单元测试,其中一个测试失败了。 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
? 我能改变什么才能做到这一点: 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. double
不会给你这种数学所需的精度。
Switch to decimal
and all will be fine. 切换到decimal
,一切都会好的。
decimal
has the precision you want. decimal
具有您想要的精度。 If you need base 10 accuracy, stick with a decimal
. 如果您需要10精度,请坚持使用decimal
。
Here is an older, but relevant article on the topic: What Every Computer Scientist Should Know About Floating-Point Arithmetic 这是一篇关于这个主题的较旧但相关的文章: 每个计算机科学家应该知道的关于浮点运算的内容
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... 例如,NUnit Assert.AreEqual有一个带有三个双精度的重载,即实际值,期望值和delta值,这是前两个值可以通过Assert传递的最大值...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.