简体   繁体   中英

implement a deterministic distribution in java

I've made the following code for a binomial distribution, can somebody tell me how I can do the same for a deterministic distribution ( this distribution has to generate the same number all the time ) It is supposed to be the most easy distribution, but I cant find a 'DeterministicDistribution' is the library.

thanks for your help.

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;
    }



}

I don't know if there is an existing library for this, but one way to do it is to use the constructor

public Random(long seed) 

as this returns an instance of Random that is determined by the seed alone.

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;
}

As long as you pass the same seed, you will get the same outcome. If you want a sequence of observations, you can increase seed by 1 each time you call the method.

If n is large, this method will be slow. I don't know how you can do it in constant time. Perhaps you can look at the source code for a non-deterministic binomial observation, and adapt it by using the Random constructor taking a seed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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