我想生成1000种气体混合物,其中三种成分具有明确的范围。每个混合的总和应该是100.我无法弄清楚如何使用for循环关联组件。
import numpy as np
comp_list = []
c1 = np.arange(80,100, 0.001)
c2 = np.arange(0,14,0.001)
c3 = np.arange(0,4, 0.001)
for i in range(10000):
comp_sum = c1[i] + c2[i] +c3[i]
if comp_sum == 100:
comp_list.append(c1[i], c2[i],c3[i])
print comp_list
答案 0 :(得分:2)
正如@AndrasDeak在评论中建议的那样,您只需执行c3 = 100 - c1 - c2
即可确保某些结果样本可以满足您的约束条件,然后从结果中获取最多1000个样本,方法:
# I created more than 1000 samples so that I have enough to slice with
In [35]: c1 = np.random.uniform(80, 100, 10000)
In [36]: c2 = np.random.uniform(0, 14, 10000)
In [37]: c3 = 100 - c1 - c2
In [38]: c3
Out[38]:
array([ 12.68861952, 4.34446942, -9.74132792, ..., 3.65083356,
-0.71305583, 9.78624485])
In [39]: masked = np.where((c3 >= 0) & (c3 <= 4))
# only take up to 1000 samples
In [40]: c1 = c1[masked][:1000]
In [41]: c2 = c2[masked][:1000]
In [42]: c3 = c3[masked][:1000]
# sum of the arrays show 100 in all
In [43]: c1 + c2 + c3
Out[43]:
array([ 100., 100., 100., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 100., 100., 100.,
这肯定不是最有效的方法,但对于简单的用例,它可以达到你想要的效果。
答案 1 :(得分:2)
您可以使用列表推导使用直接方法:
import numpy as np
c1=np.linspace(80,100,100)
carr=np.array([[c1[i],cc2,100-c1[i]-cc2] for i in range(len(c1)) for cc2 in np.arange(0,min(14,100-c1[i]),1)])
您可以使用
恢复浓度矢量c1=carr[:,0]
c2=carr[:,1]
c3=carr[:,2]
证明:
In [496]: carr.shape
Out[496]: (944, 3)
In [497]: carr.sum(1)
Out[497]: array([ 100., 100., 100., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 100., 100., 100.,
...
您必须考虑一下您选择的参数以获得大约1000个样本,因为对于每个c1
,您将拥有不同数量的c2
。然而,这将产生大致均匀的浓度集,你可能只需要小心c=100
个案例(我不是)。