Usually distributed random integers?

Is there a good way to get randomly generated integers with a normal distribution?

The first way that comes to my mind:

int rndi = (int)Math.floor(random.nextGaussian()*std);

Is there a better way?

+3
source share
4 answers

You should update the question to clarify what exactly is your use case.

According to your comment, you should not use regular distribution at all. Instead, try one of many discrete distributions, since you need integers at the end. There are many, but I would recommend one - very simple. He uses a stochastic vector as a discrete probability distribution .

:

public class DiscreteRandom {

    private final double[] probDist;

    public DiscreteRandom(double... probs) {
        this.probDist = makeDistribution(probs);
    }

    private double[] makeDistribution(double[] probs) {
        double[] distribution = new double[probs.length];
        double sum = 0;
        for (int i = 0; i < probs.length; i++) {
            sum += probs[i];
            distribution[i] = sum;
        }
        return distribution;
    }

    public int nextInt() {
        double rand = Math.random();
        int i = 0;
        while (rand > probDist[i]) i++;
        return i;
    }

    /**
     * Simple test
     */
    public static void main(String[] args) {
        // We want 0 to come 3 times more often than 1.
        // The implementation requires normalized probability
        // distribution thus testProbs elements sum up to 1.0d.
        double[] testProbs = {0.75d, 0.25d};
        DiscreteRandom randGen = new DiscreteRandom(testProbs);

        // Loop 1000 times, we expect:
        // sum0 ~ 750
        // sum1 ~ 250
        int sum0 = 0, sum1 = 0, rand;
        for (int i = 0; i < 1000; i++) {
            rand = randGen.nextInt();
            if (rand == 0) sum0++;
            else           sum1++;
        }
        System.out.println("sum0 = " + sum0 + "sum1 = " + sum1);
    }
}
+2

, . , , , . , , . ( value = 0 = 1), -2 2 99% .

, N. , , , , , , 1% . - N/2 + N * z/4, z - , . , . , .

+4

, .

java.util.Random . JavaDoc, nextGaussian() Box Muller Transform. Random.nextDouble(), . , bugfix:

Sun 48- ( ) 17 - .

, , Sun. " " , .

, PRNG.

+1

"" , , .

, "" , ...

Thus, you provide the distribution and, therefore, the probability of choosing a particular element. For fun, you can simply “mix up” your list when you need to.

+1
source

Source: https://habr.com/ru/post/1755284/


All Articles