Rasty
Rasty

Reputation: 303

Java random with low percentage on boolean array (quantile function)

I have a boolean array of aproximattely 10 000 elements. I would like to with rather low,set probability (cca 0,1-0,01) change the value of the elements, while knowing the indexes of changed elements. The code that comes to mind is something like:

int count = 10000;
Random r = new Random();
for (int i = 0; i < count; i++) {
    double x = r.nextDouble();
    if (x < rate) {
            field[i]=!field[i];
            do something with the index...
    }
}

However, as I do this in a greater loop (inevitably), this is slow. The only other possibility that I can come up with is using quantile function (gaussian math), however I have yet to find any free to use code or library to use. Do you have any good idea how to work around this problem, or any library (standard would be best) that could be used?

Upvotes: 0

Views: 260

Answers (1)

k_g
k_g

Reputation: 4463

Basically, you have set up a binomial model, with n == count and p == rate. The relevant number of values you should get, x, can be modeled as a normal model with center n*p == count*rate and standard deviation sigma == Math.sqrt(p*(1-p)/n) == Math.sqrt(rate * (1-rate) / count).

You can easily calculate

int x = (int) Math.round(Math.sqrt(rate * (1-rate) / count)
        * r.nextGaussian() + count * rate)

Then you can generate x random numbers in the range using the following code.

Set<Integer> indices = new HashSet<Integer>();
while(indices.size() < x){
     indices.add(r.nextInt(count));
}

indices will now contain the correct indices, which you can use as you wish.

You'll only have to call nextInt a little more than x times, which should be much less than the count times you had to call it before.

Upvotes: 1

Related Questions