pythonnumpy

Create an array that sums to a specific number?


I am using python. I am trying to create an array that sums to a certain number, but I want the array to be of a length of my choosing. Any idea on how to do this? For example, I want a array that sums to 1. So [.25,.25,.25,.25], but I want the numbers that are inside the array to be random, and I want my array to have a length of 98. Can someone please help?


Solution

  • Here's a simple implementation that works by building an array of 98 random numbers, finding their sum, then dividing each of the numbers by the sum so that entire array is normalised to 1.

    import random
    
    # generate a random array of 98 numbers
    numbers = [random.random() for _ in range(98)]
    print(numbers) 
    # [0.2378205280188267, 0.08942239291741982, ...]
    print(sum(numbers))
    # 48.8051742287
    
    # normalise the array to sum to 1
    normalised = [r / sum(numbers) for r in numbers]
    print(normalised) 
    # [0.004872854810521523, 0.0018322318141581963, ...]
    print(sum(normalised)) 
    # 1.0
    

    But you should probably consider using NumPy if you are doing a large number of calculations.

    Edit: the equivalent code as above but easier to read and without list comprehension:

    # build a list/array of random numbers
    numbers = []
    for _ in range(98):
        numbers.append(random.random())
    
    # get the sum of the array
    print(sum(numbers))  
    # 48.8051742287
    
    # normalise the original list using the sum
    normalised = []
    for n in numbers:
        normalised.append(n / sum(numbers))
    print(sum(normalised)) 
    # 1.0