Randomly dividing an integer (non-uniform distribution)

Sordin · Apr 2, 2022 · 1.9K views
Question
I am trying to write a code that randomly divides a number N into M parts (in other words, I want to generate M random numbers whose sum adds up to N). However, I want to allow the generated numbers to vary considerably in magnitude.   My current code generates numbers that are all in the same ballpark:     N = 1; n = rand(1,M); TOT = sum(n); numbers = (n/TOT)*N For instance, for , it yields:   0.0716 0.0184 0.0498 0.0204 0.0748 0.0528 0.0120 0.0194 0.0650 0.0721 0.0459 0.0744 0.0785 0.0248 0.0414 0.0326 0.0786 0.0778 0.0608 0.0290 As one can see, the number is so evenly distributed that all generated numbers have the same (or close) orders of magnitude.   Is there a simple way to tweak this code so that it can generate numbers that are widely different in magnitude (e.g. 0.7 and 0.01)? Any suggestions would be greatly appreciated.
Expert Answer
Profile picture of Prashant Kumar
Prashant Kumar PhD Expert
Answered Aug 13, 2026

There are any number of ways to do that, depending on exactly what you mean by "considerably". Here are a few:

 

 

%% Transform the numbers so they aren't uniform to begin with.
M=20;
N = 1;
n = rand(1,M).^10;  % Increase the exponent to increase the size variation.  A lot of numbers will be near zero.
TOT = sum(n);
numbers = (n/TOT)*N

%%  Generate progressively smaller numbers by generating each new one as a uniform(0,1) fraction of
% what is left of your total.
M=20;
n = rand(1,M);
TOT = sum(n);
cumtot = cumsum(n(1:end-1));
n(1:end-1) = n(1:end-1) .* (TOT - cumtot);
TOT = sum(n);
numbers = (n/TOT)*N
% permute(numbers) here if you don't want larger numbers to be systematically first.

 

Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!