Get in touch!Get in touch!

generate n random numbers whose sum equals a known value

python-2

Let us suppose that you have a value, which we shall call x, and you want n random numbers whose sum equals x — then the following python code will help you accomplish this. The generated values will be saved into a Spreadsheet for your convenience.

Notes:

  • Since the numbers are randomly generated, there are many possibilities. Therefore, the code allows for you to specify how many times these numbers should be generated. In this example, they are generated 256 times.
  • Each generated set of numbers is written in a specific column in the spreadsheet, so that you can view all the sets next to each other, which I found to be very convenient
  • You will observe that there are two functions in the code — one includes zeros as a possible number, the other does not
  • The code requires the xlwt python library for it to work. If you don’t have the library installed, get it from http://pypi.python.org/pypi/xlwt
  • If you want to check out other Spreadsheet libraries for python, go to http://www.python-excel.org

 

#!/usr/bin/python

#Randomize2.py
#Author: Victor Miti <http://umusebo.com>
#Tested on python 2.7

import random
import xlwt #Excel library

def constrained_sum_sample_pos(n, total):
    """Return a randomly chosen list of n positive integers summing to total.
    Each such list is equally likely to occur."""

    dividers = sorted(random.sample(xrange(1, total), n - 1))
    return [a - b for a, b in zip(dividers + [total], [0] + dividers)]

def constrained_sum_sample_nonneg(n, total):
    """Return a randomly chosen list of n nonnegative integers summing to total.
    Each such list is equally likely to occur."""

    return [x - 1 for x in constrained_sum_sample_pos(n, total + n)]

workbook = xlwt.Workbook(encoding="utf-8")
worksheet = workbook.add_sheet("generated-data")

for i in range (0, 256):
	j = 0
	#list = constrained_sum_sample_nonneg(15, 400)
	list = constrained_sum_sample_pos(15, 400)
	for n in list:
		j = j+1
		worksheet.write(j, i, n)

workbook.save("FileName.xls")


Leave a Reply