简体   繁体   中英

How can I maintain probability across multiple executions in Java

Firstly I am not the greatest with Math, so please excuse any ignorance relating to that. I am trying to maintain probability based randomness across multiple executions but I am failing. I have this input in a JSONObject

{
   "option1": 25,
   "option2":25,
   "option3" :10,
   "option4" :40
}

This is my function that selects a value from the above JSONObject based on the probability assigned:

public static String selectRandomoptions(JSONObject options) {
    String selectedOption = null;

    if (options != null) {

        int maxChance = 0;
        for (String option : options.keySet()) {
            maxChance += options.getInt(option);
        }

        if (maxChance < 100) {
            maxChance = 100;
        }

        Random r = new Random();
        Integer randomValue = r.nextInt(maxChance);

        int chance = 0;
        for (String option : options.keySet()) {
            chance += options.getInt(option);
            if (chance >= randomValue) {
                selectedOption = options.toLowerCase();
                break;
            }
        }
    }
}

the function behaves within a reasonable error margin if I call it x amount of times in a single execution ( tested 100+ calls), the problem is that I am running this every hour to generates some sample data in an event-driven app to verify our analytics process/data but we need it to be somewhat predictable, at least within a reasonable margin?

Has anyone any idea how I might approach this? I would rather not have to persist anything but I am not opposed to it if it makes sense or reduces complexity/time.

The values returned by Random.nextInt() are uniformly distributed, so that shouldn't be a problem.

I you would like to make random results repeatable, then you may want to use Random with seed .

Rather than create a new Random() object each time you want a new random number, just create the Random object once per run, and use the Random.nextInt() object once per run.

Looking at the documentation of Random() constructor,

This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.it only guarantees it to be different

that's a bit of a weaker contract than the number you get from nextInt() .

If you want to get the same sequence of numbers on each run, use the Random(long seed) or the setSeed(long seed) method of the random object. Both these methods set the seed of the generator. If you used the same seed for each invocation it's guaranteed that you will get the same sequence of numbers from the generator. Random.setSeed(long) .

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