For example I would like to generate 22 numbers between 20 and 46 with an average value of 27. And I would like the numbers to cover the range as well as possible.
E
I used an iterative approach to continuously track the current avg and the target avg while generating the numbers. Every step is directed towards bringing the cur_avg towards the target while using the RNG/
import random
def gen_target_avg(num, min, max, avg):
numbers = []
sum = 0
cur_avg = max
print "Current avg is %f: %r" % (cur_avg, numbers)
for n in range(0, num):
if avg < cur_avg:
n = random.randint(min, cur_avg)
sum += n
numbers.append(n)
elif avg > cur_avg:
n = random.randint(cur_avg, max)
sum += n
numbers.append(n)
cur_avg = sum/len(numbers)
print "Final avg is %f: %r" % (cur_avg, numbers)
>>> gen_target_avg(100, 3, 150, 25)
Current avg is 150.000000: []
Final avg is 25.000000: [81, 47, 56, 58, 23, 27, 24, 3, 7, 11, 19, 15, 19, 11, 18, 14, 24, 20, 17, 3, 121, 16, 7, 24, 6, 14, 13]
>>> gen_target_avg(100, 3, 150, 25)
Current avg is 150.000000: []
Final avg is 25.000000: [56, 3, 14, 139, 10, 10, 11, 34, 22, 26, 31, 24, 16, 19, 11, 28, 28, 6, 25, 19, 25, 17, 21]
>>> gen_target_avg(100, 3, 150, 30)
Current avg is 150.000000: []
Final avg is 30.000000: [143, 131, 38, 54, 34, 75, 31, 11, 63, 42, 38, 4, 22, 46, 27, 13, 6, 17, 14, 6, 21, 15, 3, 30, 15, 29, 28, 4, 32, 9, 17, 22, 10, 28, 11, 26]