累积二项式概率 C#

Cumulative Binomial Probability C#

我正在尝试计算 'n' 试验的累积二项式概率,其中 'p' 概率和 'r' 作为每次试验的成功结果。我编写了以下有时有效但并非总是有效的代码:

Console.WriteLine ();
Console.WriteLine ("B~(n, p)");

incorrectN:

Console.WriteLine ("Enter value of 'n': ");
int n = Convert.ToInt32 (Console.ReadLine ());

if (n < 0) {
    Console.WriteLine ("ERROR: 'n' must be greater than 0");
    goto incorrectN;
}

incorrectP:

Console.WriteLine ();
Console.WriteLine ("Enter value of 'p': "); 
double p = Convert.ToDouble (Console.ReadLine ());

if (p > 1) {
    Console.WriteLine ();
    Console.WriteLine ("ERROR: 'p' must be between 0 and 1");
    goto incorrectP;
}

Console.WriteLine ();

incorrectS:

int r = GetR();
int k = r;

double binomTotal = 0;

for (int j = r + 1; j > 0; j--) {

  int nCr = Factorial(n) / (Factorial(n - (r - k)) * Factorial(r - k));

  binomTotal = binomTotal + nCr * Math.Pow(p, (r - k)) * Math.Pow(1 - p, (n - (r - k)));

  k--;
}

Console.WriteLine();
Console.WriteLine(binomTotal);

P.S。我在 class 的其他地方编写了 GetR()Factorial() 函数,其中 GetR() 向用户询问 'r' 的值,而 Factorial() 是定义如下:

public static int Factorial(int x)
{
    return x <= 1 ? 1 : x * Factorial(x - 1);
}

我用值 n = 10, p = 0.5r = 5 测试了代码,输出是 0.623046875,这是正确的。但是,当我使用 n = 13, p = 0.35r = 7 时,我得到 0.297403640622647 而不是 0.9538

如有任何帮助,我们将不胜感激。

变化:

public static int Factorial(int x)
    {
        return x <= 1 ? 1 : x * Factorial(x - 1);
    }

收件人:

public static double Factorial(double x)
    {
        return x <= 1 ? 1 : x * Factorial(x - 1);
    }

因为 Factorial(13) 对于 Int32 来说太大了。

加上你自己的回答:

public static double Factorial(double x)
{
    return x <= 1 ? 1 : x * Factorial(x - 1);
}

接受一个double参数,也就是说x不限制为整数。 所以你可以像这样调用你的 Factorial 方法。

var fac1 = Factorial(1.4);
var fac2 = Factorial(2.7);

但是,这没有意义,因为阶乘 n! 仅针对 n 定义*,这意味着 1.7! 未定义。

因此,您应该使用 long 而不是使用 double 并允许无效输入,它的范围比 int.

public static long Factorial(long x)
{
    return x <= 1 ? 1 : x * Factorial(x - 1);
}

* 在某些情况下,阶乘也可以与实数值一起使用 - 例如通过使用 gamma 函数 - 但我认为它们与您的用例无关,因此您不应允许无效参数。