number generator

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Mar 10 08:45:30 EST 2007


On Fri, 09 Mar 2007 18:41:39 +0000, Dennis Lee Bieber wrote:

> On 9 Mar 2007 06:44:01 -0800, "cesco" <fd.calabrese at gmail.com> declaimed
> the following in comp.lang.python:
> 
>> I have to generate a list of N random numbers (integer) whose sum is
>> equal to M. If, for example, I have to generate 5 random numbers whose
>> sum is 50 a possible solution could be [3, 11, 7, 22, 7]. Is there a
>> simple pattern or function in Python to accomplish that?
>>
> 	Well... Just that the last number is not random -- it has to equal
> (using your limit of 50 and 5 numbers):
> 
> fifth = 50 - sum(first, second, third, fourth) 

Doesn't mean that it isn't random. After all, the first four numbers are
random, therefore their sum is random. 50 - (something random) is also
random.

In practice, one would deterministically generate the last number needed,
but that last number is unpredictable because the first four numbers are
unpredictable. 

Remember that random numbers are not necessarily unconstrained, nor are
they necessarily uniformly distributed. We blithely talk about "random
numbers", but of course there is a constraint that we're selecting from a
finite range. Any finite range of numbers, no matter how big, is a
vanishingly small percentage of all the possible numbers.



-- 
Steven.




More information about the Python-list mailing list