使用numpy模拟1000种含有三种成分的气体混合物

Using numpy to simulate 1000 gas mixtures containing three components

我想生成 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

正如@AndrasDeak 在评论中建议的那样,您可以简单地执行 c3 = 100 - c1 - c2 以确保 SOME 结果样本可以满足您的限制,然后最多只需要 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.,

这肯定不是最有效的方法,但对于简单的用例,它可以实现您想要的。

您可以通过使用列表推导来使用直接方法:

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 个案例(我不是)。