Re: Generate a sequence of random numbers that sum up to 1?



Alex Martelli wrote:
Such total disuniformity, where the very distribution of each value is
skewed by the preceding one, may still be "random" for some sufficiently
vague meaning of "random", but my intuition suggests it's unlikely to
prove satisfactory for the OP's purposes.

It does seem very odd. If you could restrict the range, you could get an unskewed distribution. Set range = (0, 2*sum/cnt) and you can generate cnt numbers whose sum will tend towards sum (because the average value will be sum/cnt):

target_sum = 1
cnt = 100
max = 2.0 * target_sum / cnt # 0.02
nums = [random.uniform(0,max) for x in range(0,cnt)]
real_sum = sum(nums) # 0.975... in one sample run

If the sum has to be exact, you can set the last value to reach it:

nums[-1] = target_sum - sum(nums[:-1])
print sum(nums) # 1.0

which skews the sample ever so slightly. And check for negatives in case the sum exceeded the target.

If the exact count doesn't matter, just generate random nums until you're within some delta of the target sum.

Basically, there usually better options to the problem as originally posed. Actually, now that I reread it the OP never said the range had be [0,1). So maybe we read too much into the original phrasing. If you need anything resembling a uniform distribution, scaling the results afterward is not the way to go.
.



Relevant Pages

  • Re: Basic Statistical Mechanics Questions
    ... still admits a multiplier that makes it exact. ... The mechanical work is defined through a differential form: ... weighted sum of the form: ...
    (sci.physics.research)
  • Re: Feature suggestion: sum() ought to use a compensated summation algorithm
    ...  Your algorithm is specific to floats. ... sum() seems to be most useful for numeric types (i.e. those ... may be either exact or inexact (e.g. floating point ... compensated summation for built-in floating point types. ...
    (comp.lang.python)
  • Re: Feature suggestion: sum() ought to use a compensated summation algorithm
    ... Your algorithm is specific to floats. ... Or is this just a special exception to prevent the misuse of sum to join strings? ... For exact types it does not make sense to use compensated summation, and sumcannot decide whether a user-defined type is exact or inexact. ...
    (comp.lang.python)
  • Re: summary of {1/n}
    ... I'm guessing that by summary, ... is not exact, ... where gamma is the Euler-Mascheroni constant ... The asymptotic expansion is ...
    (sci.math)
  • Re: [PHP] array_sum($result)=100
    ... This seems to be nice method, I tried to do translate it to PHP put ... >> I have array of numbers and I want to get out of it a list of numbers ... > calculate the sum of numbers in loops (end loop when the sum is larger ... first number under the target sum ...
    (php.general)