Your task is to write a program or a function that outputs n
random numbers from interval [0,1] with fixed sum s
.
Input
n, n≥1
, number of random numbers to generate
s, s>=0, s<=n
, sum of numbers to be generated
Output
A random n
-tuple of floating point numbers with all elements from the interval [0,1] and sum of all elements equal to s
, output in any convenient unambiguous way. All valid n
-tuples have to be equally likely within the limitations of floating point numbers.
This is equal to uniformly sampling from the intersection of the points inside the n
-dimensional unit cube and the n-1
-dimensional hyperplane that goes through (s/n, s/n, …, s/n)
and is perpendicular to the vector (1, 1, …, 1)
(see red area in Figure 1 for three examples).
Figure 1: The plane of valid outputs with n=3 and sums 0.75, 1.75 and 2.75
Examples
n=1, s=0.8 → [0.8]
n=3, s=3.0 → [1.0, 1.0, 1.0]
n=2, s=0.0 → [0.0, 0.0]
n=4, s=2.0 → [0.2509075946818119, 0.14887693388076845, 0.9449661625992032, 0.6552493088382167]
n=10, s=9.999999999999 → [0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999]
Rules
- Your program should finish under a second on your machine at least with
n≤10
and any valid s. - If you so wish, your program can be exclusive on the upper end, i.e.
s<n
and the output numbers from the half-open interval [0,1) (breaking the second example) - If your language doesn't support floating point numbers, you can fake the output with at least ten decimal digits after the decimal point.
- Standard loopholes are disallowed and standard input/output methods are allowed.
- This is code-golf, so the shortest entry, measured in bytes, wins.
This is equal to uniformly sampling from the intersection
- i can see a program choosing randomly from just the corners of that intersection. Would that be valid ? \$\endgroup\$s==0 or s==3
. For all other values ofs
, the plane has nonzero area and you have to uniform-randomly choose a point on that plane. \$\endgroup\$s=2.99999999999, n=3
? May we generate random reals in multiples of, say,1e-9
? \$\endgroup\$