Divide a number N into K numbers
Show older comments
How to divide a number into the sum of many numbers. For example, 64 is divided into the sum of eight numbers, each of which is not less than 1 and not more than 16.
Accepted Answer
More Answers (2)
Image Analyst
on 6 Mar 2021
1 vote
randfixedsum():
This generates m random n-element column vectors of values, [x1;x2;...;xn], each with a fixed sum, s, and subject to a restriction a<=xi<=b. The vectors are randomly and uniformly distributed in the n-1 dimensional space of solutions. This is accomplished by decomposing that space into a number of different types of simplexes (the many-dimensional generalizations of line segments, triangles, and tetrahedra.) The 'rand' function is used to distribute vectors within each simplex uniformly, and further calls on 'rand' serve to select different types of simplexes with probabilities proportional to their respective n-1 dimensional volumes. This algorithm does not perform any rejection of solutions - all are generated so as to already fit within the prescribed hypercube.
Cite As
Roger Stafford (2021). Random Vectors with Fixed Sum (https://www.mathworks.com/matlabcentral/fileexchange/9700-random-vectors-with-fixed-sum), MATLAB Central File Exchange. Retrieved March 6, 2021.
Image Analyst
on 6 Mar 2021
Here's one way. (Hopefully it's not your homework. Tag it as homework if it is.)
N = 8;
r = 1 + 15 * rand(10000, N)
% Compute sum of each row
theSums = sum(r, 2)
% Find sums more than 64
index64 = theSums >= 64;
% Set below 64 to infinity
theSums(~index64) = inf;
% Find the one closest to 64:
[value, index] = min(theSums)
% Extract those N numbers
theEightNumbers = r(index, :)
% Rescale so the sum is exactly 64
theEightNumbers = theEightNumbers * 64 / sum(theEightNumbers)
% Double Check
sum(theEightNumbers)
You'll see
theEightNumbers =
6.1735 2.1348 10.4723 1.6452 14.5796 5.4155 12.5308 11.0483
ans =
64
Categories
Find more on Choose a Solver in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!