Jackson Tale
Jackson Tale

Reputation: 25812

How to use Random.nextGaussian() to generate N doubles that sum to 1

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

Answers (1)

Andy Turner
Andy Turner

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

Related Questions