繁体   English   中英

在java中实现确定性分布

[英]implement a deterministic distribution in java

我已经为二项式分布编写了以下代码,有人可以告诉我如何对确定性分布执行相同的操作(此分布必须始终生成相同的数字)它应该是最简单的分布,但是我找不到“DeterministicDistribution”是图书馆。

谢谢你的帮助。

import java.util.HashMap;
import org.apache.commons.math3.distribution.AbstractIntegerDistribution;
import org.apache.commons.math3.distribution.BinomialDistribution;

public class Binomial extends Distribution
{
    AbstractIntegerDistribution distribution;



    @Override
    public void setParameters(HashMap<String,?> hm)
    {
    try
    {
         int n = 0;
         double p =0.0;
            if (hm.containsKey("n"))
                n = Integer.parseInt((String) hm.get("n"));
            else
                throw new Exception("Exception: No n-value found");
                    if(hm.containsKey("p"))
                         p = Double.parseDouble((String) hm.get("p"));
                    else
                        throw new Exception("Exception: No p-value found");
        distribution = new BinomialDistribution(n,p);
    }
    catch(Exception e)
    {
        System.out.println(e.getMessage());
    }
    }


    @Override
    public int getSample()
   {
       int a = distribution.sample();
       return a;
   }  

    public AbstractIntegerDistribution getDistribution() 
    {
        return distribution;
    }



}

我不知道是否有一个现有的库,但一种方法是使用构造函数

public Random(long seed) 

因为这会返回一个Random实例,该实例仅由种子决定。

public static int binomialObservation(long seed, int n, double p) {
    if (n < 0)
        throw new IllegalArgumentException();
    if (p <= 0 || n == 0)
        return 0;
    if (p >= 1)
        return n;
    Random random = new Random(seed);
    int count = 0;
    for (int i = 0; i < n; i++)
        if (random.nextDouble() <= p)
            count++;
    return count;
}

只要传递相同的种子,就会得到相同的结果。 如果你想要一个观察序列,你可以在每次调用该方法时将seed增加1

如果n很大,这种方法会很慢。 我不知道你怎么能在恒定的时间内做到这一点。 也许您可以查看非确定性二项式观察的源代码,并通过使用Random构造函数获取种子来对其进行调整。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM