2016-01-18 44 views
-1

我試圖產生8號與代碼如下列表:生成基於約束步驟程序號碼列表

import numpy as np 
import pandas as pd 

n2 = np.random.uniform(0.1, 1.5) 
c2 = np.random.uniform(4,14) 
c3 = np.random.uniform(0.1,2.9) 
ic4 = np.random.uniform(0.01,1) 
nc4 = np.random.uniform(0.01,1) 
ic5 = np.random.uniform(0,0.2) 
nc5 = np.random.uniform(0,0.01) 

comp_list = [] 

for i in range(1): 
    if n2/c2 <= 0.11: 
     comp_list.append(c2) 
     comp_list.append(n2) 
    if c3/c2 <= 0.26: 
     comp_list.append(c3) 
    if ic4/c3 <= 0.27: 
     comp_list.append(ic4) 
    if nc4/ic4 <= 1: 
     comp_list.append(nc4) 
    if ic5/nc4 <= 0.06: 
     comp_list.append(ic5) 
    if nc5/ic5 <= 0.25: 
     comp_list.append(nc5) 

    sum = n2+c2+c3+ic4+nc4+ic5+nc5 
    c1 = 100-sum 
    comp_list.append(c1) 

df = pd.Series(comp_list) 

print df 

然而,當我運行的代碼中,量輸出的數字是不相符的,並且可以從3至5,例如範圍,1個運行會給我:

0  1.560 
1  0.251 
2  0.008 
3  86.665 

第二次運行可以給我:

0  12.929 
1  1.015 
2  2.126 
3  0.093 
4  0.0025 
5  83.376 

我不知道爲什麼輸出不一致。

也許我需要迭代通過隨機分佈,直到所有的if語句都滿意?還是我錯過了明顯的東西?

+0

因爲你用'np.random.uniform()'生成隨機數字? – gtlambert

+0

我需要隨機生成的數字來滿足約束(即<= 0.2)。有沒有辦法檢查隨機數是否滿足約束條件?一種迭代? – Joey

+0

你還沒有解釋你想要做什麼或你的期望。 – pjs

回答

1

你想在while循環中包含所有的東西。滾動您的所有號碼。如果他們都滿足您的條件,請創建必要的列表。只要其中一個條件不滿足,所有數字都將被重新發送。

你想要重新捲動所有數字的原因是它們都是彼此獨立的。例如,c2涉及n2/c2c3/c2。如果n2/c2得到滿足並且您保留這兩個數字,則您可以使用c3的值來滿足條件c3/c2受您已經爲c2選擇的內容的限制。

import numpy as np 

while True: 
    n2 = np.random.uniform(0.1, 1.5) 
    c2 = np.random.uniform(4,14) 
    c3 = np.random.uniform(0.1,2.9) 
    ic4 = np.random.uniform(0.01,1) 
    nc4 = np.random.uniform(0.01,1) 
    ic5 = np.random.uniform(0,0.2) 
    nc5 = np.random.uniform(0,0.01) 

    if (n2/c2 <= 0.11 and 
     c3/c2 <= 0.26 and 
     ic4/c3 <= 0.27 and 
     nc4/ic4 <= 1 and 
     ic5/nc4 <= 0.06 and 
     nc5/ic5 <= 0.25): 

     comp_list = [n2, c2, c3, ic4, nc4, ic5, nc5] 
     comp_list.append(100 - sum(comp_list)) 
     break 

編輯:爲了產生這樣一個列表的列表,迭代將該代碼作爲根據需要多次和每次comp_list結果追加。

big_list = [] 
for _ in range(10): 
    # while stuff 
    big_list.append(comp_list) 

如果這是你希望在你的代碼中的不同位置運行的東西,你可以把它放在一個函數中。

def generate_numbers(): 
    while True: 
     ... 
    return comp_list 

然後你可以做big_list = [generate_numbers() for _ in range(10)]

+0

非常感謝您的回覆。請問我可以多次運行while循環來獲得一組10個列表(10個熊貓數據框中的行? – Joey

+1

@Joey我已經更新了我的答案 – Reti43

+0

太棒了!這幫了很大的忙! – Joey