Distribute a quantity randomly

I'm starting a project where I'm simulating an explosion of an object. I want to randomly distribute the total mass of the object that explodes into the fragments. For example, if the object has a mass of 3 kg and breaks into 3 fragments their masses could be 1, 0.5, 1.5 respectively. I want to do the same thing with energy and other things. Also, I would like to have control over the random distribution used.

I think I could do this simply by generating a random number, somehow relate it to the quantity I want to distribute and keep doing that while subtracting to the total pool. The problem with this approach is that on first sight it doesn't seem very efficient, and it may give problems for a fixed number of fragments.

So the question is, is there an algorithm or an efficient way to do this? An example will be thoroughly appreciated.

Upvotes: 2

Views: 1015

Answers (2)

Matt Timmermans
Matt Timmermans

Reputation: 59144

For this problem, the first thing I would try is this:

  1. Generate N-1 random numbers between 0 and 1
  2. Sort them
  3. Raise them to the xth power
  4. Multiply the N differences between 0, successive numbers, and 1, by the quantity you want to distribute. Of course all these differences add up to 1, so you'll end up distributing exactly the target quantity.

A nice advantage of this method is that you can adjust the parameter x to get an aesthetically pleasing distribution of chunks. Natural explosions won't produce a uniform distribution of chunk sizes, so you'll want to play with this.

Upvotes: 2

Guy Marino
Guy Marino

Reputation: 439

So here's a generic algorithm that might work for you:

  1. Generate N random numbers using a distribution of your choosing
  2. Find the sum of all the numbers
  3. Divide each number by its sum
  4. Multiply by the fixed total mass of your object

This will only take O(N) time, and will allow you to control the distribution and number of chunks.

Upvotes: 4

Related Questions