Reputation: 25812
I want to generate N random doubles that their sum is 1.
Also, the N random doubles should obey normal distribution.
I understand nextGuassian()
in Random
can generate normal distributed number.
But how to achieve the goal above?
Upvotes: 0
Views: 346
Reputation: 140309
double[] generateNRandomDoublesWhichSumToOne(Random random, int n) {
if (random == null) throw new NullPointerException();
if (n <= 0) throw new IllegalArgumentException();
double[] values = new double[n];
double sum = 0;
for (int i = 0; i < n; ++i) {
values[i] = random.nextGaussian();
sum += values[i];
}
for (int i = 0; i < n; ++i) {
values[i] /= sum;
}
return values;
}
Upvotes: 2