从二项分布生成数字的数值算法 [英] Numerical algorithm to generate numbers from Binomial distribution

查看:70
本文介绍了从二项分布生成数字的数值算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从二项式(n,p)分布中生成随机数.

I need to generate random numbers from Binomial(n, p) distribution.

一个二项式(n,p)随机变量是n个统一变量的总和,这些变量取1的概率为p.在伪代码中,x=0;for(i=0; I 将生成二项式(n, p).

A Binomial(n, p) random variable is sum of n uniform variables which take 1 with probability p. In pseudo code, x=0; for(i=0; I<n; ++I) x+=(rand()<p?1:0); will generate a Binomial(n, p).

我需要为小的和非常大的 n 生成这个,例如 n = 10^6 和 p=0.02.有没有什么快速的数值算法来生成它?

I need to generate this for small as well as really large n, for example n = 10^6 and p=0.02. Is there any fast numerical algorithm to generate it?

编辑 -

现在这就是我所拥有的近似值(以及用于精确泊松和正态分布的函数)-

Right now this is what I have as approximation (along with functions for exact Poisson and Normal distribution)-

    public long Binomial(long n, double p) {
        // As of now it is an approximation
        if (n < 1000) {
            long result = 0;
            for (int i=0; i<n; ++i)
                if (random.NextDouble() < p) result++;
            return result;
        }
        if (n * p < 10) return Poisson(n * p);
        else if (n * (1 - p) < 10) return n - Poisson(n * p);
        else {
            long v = (long)(0.5 + nextNormal(n * p, Math.Sqrt(n * p * (1 - p))));
            if (v < 0) v = 0;
            else if (v > n) v = n;
            return v;
        }
    }

推荐答案

如果你愿意付费,那就看看NMath 来自 Centerspace.

If you are willing to pay, then take a look at NMath by Centerspace.

否则,Stats程序R使用的C代码是here,并且应该可以直接移植到 C#.

Otherwise, the C code used by the Stats program R is here, and should be straightforward to port to C#.

Practical Numerical 的 p178 上有关于为此创建方法的详细信息(包括代码)使用 C# 的方法 作者:Jack Xu.

There are details (inc. code) on creating a method for this on p178 of Practical Numerical Methods with C# by Jack Xu.

另一个一个免费的 C# 库,可以满足您的需求.

ANOTHER A free C# library that does what you want.

这篇关于从二项分布生成数字的数值算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆