有三个变量 x 1 , x 2 , x 3 \ x_1,x_2,x_3 x1,x2,x3
生成满足约束的值:
x 1 + x 2 + x 3 = n \ x_1+x_2+x_3=n x1+x2+x3=n
a 1 < x 1 < b 1 , a 2 < x 2 < b 2 , a 3 < x 3 < b 3 \ a_1<x_1<b_1 , a_2<x_2<b_2,a_3<x_3<b_3 a1<x1<b1,a2<x2<b2,a3<x3<b3
思路:
1、 a 3 < x 3 < b 3 \ a_3<x_3<b_3 a3<x3<b3,所以 a 3 < n − x 1 − x 2 < b 3 \ a_3<n-x_1-x_2<b_3 a3<n−x1−x2<b3
2、由1得, n − x 1 − b 3 < x 2 < n − x 1 − a 3 \ n-x_1-b_3<x_2<n-x_1-a_3 n−x1−b3<x2<n−x1−a3
3、由2得, n − x 1 − b 3 > a 2 , n − x 1 − a 3 < b 2 \ n-x_1-b_3>a_2,n-x_1-a_3<b_2 n−x1−b3>a2,n−x1−a3<b2,所以, x 1 ∈ [ n − ( b 2 + b 3 ) , n − ( a 2 + a 3 ) ] \ x_1\in [n-(b_2+b_3),n-(a_2+a_3)] x1∈[n−(b2+b3),n−(a2+a3)]
步骤:
1、生成 x 1 ∈ [ n − ( b 2 + b 3 ) , n − ( a 2 + a 3 ) ] \ x_1\in [n-(b_2+b_3),n-(a_2+a_3)] x1∈[n−(b2+b3),n−(a2+a3)]
2、生成 x 2 ∈ [ n − ( x 1 + b 3 ) , n − ( x 1 + a 3 ) ] \ x_2\in [n-(x_1+b_3),n-(x_1+a_3)] x2∈[n−(x1+b3),n−(x1+a3)]
3、生成 x 3 = n − x 1 − x 2 \ x_3=n-x_1-x_2 x3=n−x1−x2
# python 3.6
import random
# 递归生成随机数
def generate_randval(x_low, x_up, x_sum, y):
if len(x_low)==1:
y.append(x_sum)
print(x_sum)
else:
a = max(x_sum-sum(x_up[1:len(x_up)]), x_low[0])
b = min(x_sum-sum(x_low[1:len(x_low)]), x_up[0])
temp = random.uniform(a, b)
y.append(temp)
print(temp)
x_low = x_low[1:len(x_low)]
x_up = x_up[1:len(x_up)]
x_sum = x_sum - temp
generate_randval(x_low, x_up, x_sum, y)
if __name__=="__main__":
x_low = [1, 2, 3]
x_up = [3, 6, 9]
x_sum =10 # 在6和18之间
y = []
generate_randval(x_low, x_up, x_sum, y)
有三个变量 x 1 , x 2 , x 3 \ x_1,x_2,x_3 x1,x2,x3
生成满足约束的值:
x 1 + x 2 + x 3 = n \ x_1+x_2+x_3=n x1+x2+x3=n
a 1 < x 1 < b 1 , a 2 < x 2 < b 2 , a 3 < x 3 < b 3 \ a_1<x_1<b_1, a_2<x_2<b_2,a_3<x_3<b_3 a1<x1<b1,a2<x2<b2,a3<x3<b3
a 1 = a 2 = a 3 , b 1 = b 2 = b 3 , c 1 = c 2 = c 3 \ a_1=a_2=a_3, \ b_1=b_2=b_3, \ c_1=c_2=c_3 a1=a2=a3, b1=b2=b3, c1=c2=c3
思路:
1、 x 1 = y 1 / ( y 1 + y 2 + y 3 ) ∗ n \ x_1=y_1/(y_1+y_2+y_3)*n x1=y1/(y1+y2+y3)∗n,所以 a 1 < y 1 / ( y 1 + y 2 + y 3 ) ∗ n < b 1 \ a_1<y_1/(y_1+y_2+y_3)*n<b_1 a1<y1/(y1+y2+y3)∗n<b1
2、若 a 1 < y 1 < b 1 \ a_1<y_1<b_1 a1<y1<b1,所以 0 < 1 / ( y 1 + y 2 + y 3 ) ∗ n < 1 \ 0<1/(y_1+y_2+y_3)*n<1 0<1/(y1+y2+y3)∗n<1
步骤:
1、生成 y 1 ∈ [ a 1 , b 1 ] \ y_1\in [a_1,b_1] y1∈[a1,b1], y 2 ∈ [ a 2 , b 2 ] \ y_2\in [a_2,b_2] y2∈[a2,b2], y 3 ∈ [ a 3 , b 3 ] \ y_3\in [a_3,b_3] y3∈[a3,b3]
2、如果 y 1 + y 2 + y 3 > n \ y_1+y_2+y_3 >n y1+y2+y3>n, 生成 x 1 = y 1 / ( y 1 + y 2 + y 3 ) ∗ n \ x_1=y_1/(y_1+y_2+y_3)*n x1=y1/(y1+y2+y3)∗n, x 2 = y 2 / ( y 1 + y 2 + y 3 ) ∗ n \ x_2=y_2/(y_1+y_2+y_3)*n x2=y2/(y1+y2+y3)∗n, x 3 = y 3 / ( y 1 + y 2 + y 3 ) ∗ n \ x_3=y_3/(y_1+y_2+y_3)*n x3=y3/(y1+y2+y3)∗n
3、如果 y 1 + y 2 + y 3 < n \ y_1+y_2+y_3 <n y1+y2+y3<n,生成 x 1 = y 1 ∗ n / ( y 1 + y 2 + y 3 ) \ x_1=y_1*n/(y_1+y_2+y_3) x1=y1∗n/(y1+y2+y3), x 2 = y 2 ∗ n / ( y 1 + y 2 + y 3 ) \ x_2=y_2*n/(y_1+y_2+y_3) x2=y2∗n/(y1+y2+y3), x 3 = y 3 ∗ n / ( y 1 + y 2 + y 3 ) \ x_3=y_3*n/(y_1+y_2+y_3) x3=y3∗n/(y1+y2+y3)