Generating random integers within range with a probability distribution
Asked Answered
C

2

7

I have a problem where I want to generate a set of random integer values between 1 and 5 inclusive using a probability distribution.

Poisson and Inverse Gamma are two distributions that show the characteristics I am after (majority at mean, less higher numbers) that I have found.

I am looking at using Apache Commons Math but I wasn't sure how to generate the numbers I wanted using the distributions available.

Cryogen answered 8/5, 2013 at 8:8 Comment(1)
Well, here's a starting point: commons.apache.org/proper/commons-math/javadocs/api-3.2/org/…Drab
P
12

From your problem description, it sounds like you actually want a sample generated from a discrete probability distribution, and you can use EnumeratedIntegerDistribution for this purpose. Choose appropriate probabilities for each of your integers, maybe something like the following would meet your needs:

int[] numsToGenerate           = new int[]    { 1,   2,    3,   4,    5   };
double[] discreteProbabilities = new double[] { 0.1, 0.25, 0.3, 0.25, 0.1 };

EnumeratedIntegerDistribution distribution = 
    new EnumeratedIntegerDistribution(numsToGenerate, discreteProbabilities);

int numSamples = 100;
int[] samples = distribution.sample(numSamples);

Just tweak the discreteProbabilities values to whatever you require.

Peripatetic answered 8/5, 2013 at 8:45 Comment(1)
is there also a EnumeratedDistribution for Objects?Perkins
M
0

I would just produce uniformly distributed random numbers then pass them into the distribution function you want, so if the distribution function was x^2

import java.util.ArrayList;

import java.util.Random;



    public class Test{

        public static void main(String args[]){
            Test t=new Test();
        }

        public Test(){

            Random rnd=new Random();

            ArrayList<Double> data=new ArrayList<Double>();

            for(int i=0;i<1000;i++){
                data.add(useFunction(rnd.nextDouble()));
            }

        }

        public double useFunction(double in){
            return in*in;
        }
    }
Mccoy answered 8/5, 2013 at 8:13 Comment(1)
That said if theres an inbuilt function in Apache thats going to be easierMccoy

© 2022 - 2024 — McMap. All rights reserved.