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