简体   繁体   English

如何使数字总和等于1

[英]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.

相关问题 如何获得最小的输入数字总和? - How do i get the lowest sum of input numbers? 如何让我的程序选择除数组之和的数字? - How can I make my program select numbers that divide the sum of numbers from an array? 如何确定一组值之和的任何组合是否等于某个值? - How do I determine if any combination of the sum of a set of values is equal to a certain value? 在 C# 中,如何在数组中存储随机数等于某些总和的次数? - In C#, how do I store the amount of times random numbers equal certain sums in an array? C#用两个随机数求和,但必须等于用户输入 - C# Make a sum with two random numbers but it must equal the users input 如何使随机数遵循某些自定义规则? - How do I make random numbers follow certain custom rules? 如何在Visual Studio中使自动版本号工作 - How do I make automatic version numbers work in Visual Studio 如何制作只接受数字的文本框? - How do I make a textbox that only accepts numbers? C# 我必须找到等于它们总和的 4 个数字之间的所有可能组合,运算符优先级问题 - C# I have to find all possibe combinations between 4 numbers that are equal to their sum, problem with operator precedence 如何创建一个 function 将两个数字作为 arguments 并返回它们的总和? - How do I create a function that takes two numbers as arguments and return their sum?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM