this is a followup question from link Generate multiple random numbers to equal a value in python
In this problem, I have used the code given by Dr. Dickinson to generate random numbers whose sum = fixed number N. However, I have additional constraints in the problem. Each number generated must be within 50% of its nominal (original) value. For example, if the nominal value of the 5 numbers {x1,x2,x3,x4,x5}= {100,100,50,150,100}, then x1 can vary within (50,150), x2 can vary within (50,150), x3 can vary within (25,75) and so on. However, the sum of x1+x2+x3+x4+x5 = fixed number N.
To do this, I have added the following code.
import random
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
def constrained_sum_sample_pos(n, total):
dividers = sorted(random.sample(range(1, total), n - 1))
return [a - b for a, b in zip(dividers + [total], [0] + dividers)]
nominal = [100,100,50,150,100]
count=0
l=[]
for x in range(1,10000):
tempValue = np.asarray(constrained_sum_sample_pos(5, 500))
temp = np.divide(np.absolute(nominal - tempValue), nominal)
if (temp <= 0.5).all():
l.append(tempValue)
count = count + 1
print(np.asarray(l))
finalArray = np.asarray(l)
print(finalArray)
np.savetxt('file1.txt', finalArray,'%5.2f')
print(len(l))
print(np.amax(finalArray,axis=0))
print(np.amin(finalArray,axis=0))
n, bins, patches = plt.hist(finalArray[:,0], 5, facecolor='blue', alpha=0.5)
plt.show()
n, bins, patches = plt.hist(finalArray[:,1], 5, facecolor='blue', alpha=0.5)
plt.show()
n, bins, patches = plt.hist(finalArray[:,2], 5, facecolor='blue', alpha=0.5)
plt.show()
n, bins, patches = plt.hist(finalArray[:,3], 5, facecolor='blue', alpha=0.5)
plt.show()
n, bins, patches = plt.hist(finalArray[:,4], 5, facecolor='blue', alpha=0.5)
plt.show()
Basically, what this does is samples numbers using constrained_sum_sample_pos(n, total):
function and then checks if each individual number satisfies the constraints. If not, the numbers are rejected. I have two questions:
- Is there any easier way to do it?
- What is the distribution of such numbers generated?
I have looked at Dirichlet distribution however, I am not able to understand how to realize the additional constraints.