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
So I also used the random number generator. In addition, in order to meet the specification to cover the range as well as possible, I also calculated the standard deviation, which is a good measure of spread. So whenever a sample set meets the criteria of mean of 27, I compared it to previous matches and constantly choose the samples that have the highest std dev (mean always = 27). SO in my script, I did 5 trials, and you can see the output that the final answer matches the samples_list that had highest std dev. Note that Python 3.4 or higher is needed to use statistics module. If you're using Python 2, then you can replace the stdev function with of your own (which you can easily find on Google or Stackoverflow)
import random as rd
import statistics as st
min_val = 20
max_val = 46
sample_count = 22
expected_mean = 27
num_of_trials = 5
def get_samples_list(min_v, max_v, s_count, exp_mean):
target_sum = sample_count * expected_mean
samples_list = []
curr_stdev_max = 0
for trials in range(num_of_trials):
samples = [0] * sample_count
while sum(samples) != target_sum:
samples = [rd.randint(min_v, max_v) for trial in range(s_count)]
print ("Mean: ", st.mean(samples), "Std Dev: ", st.stdev(samples), )
print (samples, "\n")
if st.stdev(samples) > curr_stdev_max:
curr_stdev_max = st.stdev(samples)
samples_best = samples[:]
return samples_best
samples_list = get_samples_list(min_val, max_val, sample_count, expected_mean)
print ("\nFinal list: ",samples_list)
samples_list.sort()
print ("\nSorted Final list: ",samples_list)
Here is the output:
Mean: 27 Std Dev: 6.90755280213519
[34, 30, 39, 21, 23, 32, 22, 23, 22, 20, 27, 30, 29, 20, 32, 24, 42, 20, 39, 24, 20, 21]
Mean: 27 Std Dev: 6.07100838882165
[21, 21, 34, 27, 35, 22, 29, 34, 24, 21, 20, 22, 20, 23, 26, 29, 28, 31, 30, 41, 21, 35]
Mean: 27 Std Dev: 6.2105900340811875
[26, 27, 26, 26, 25, 42, 32, 23, 21, 34, 23, 20, 25, 25, 21, 27, 40, 21, 26, 26, 37, 21]
Mean: 27 Std Dev: 8.366600265340756
[27, 22, 22, 44, 41, 21, 28, 36, 21, 23, 21, 25, 20, 20, 39, 46, 23, 25, 21, 23, 20, 26]
Mean: 27 Std Dev: 6.347102826149446
[21, 30, 20, 41, 25, 23, 39, 26, 27, 20, 28, 23, 29, 24, 20, 40, 27, 27, 22, 25, 34, 23]
Final list: [27, 22, 22, 44, 41, 21, 28, 36, 21, 23, 21, 25, 20, 20, 39,
46, 23, 25, 21, 23, 20, 26]
Sorted Final list: [20, 20, 20, 21, 21, 21, 21, 22, 22, 23, 23, 23, 25, 25,
26, 27, 28, 36, 39, 41, 44, 46]
>>>