2017-09-24 83 views
-1

我有以下函數來計算兩個不同的東西:在另一個函數使用函數的變量

def LCM(X0, a, c, m, n): #Generates "n" numbers of random numbers# with given parameters. 
    X = [] 
    X.append(X0) 
    for i in range(n): 
     X.append(float((a*X[i]+c) % m)) 
     X[i] = X[i]/m 
    del X[0] 
    X[n-1] = X[n-1]/m 

    plt.hist(X) 
    plt.title("LCM Frequency Histogram") 
    plt.show() 
    print "For this example, the LCM generated a good quality uniform distribution." 
    print "However, it should be also noted that every 2000 generations," 
    print "the numbers are repeated." 
    return X[:10] #Show only the first 10 values of the list. 

def exponential(lambdavalue): 
    Z =[] 
    for i in range(10000): 
     Z.append(float(-(1/lambdavalue)*math.log(1-X[i]))) 
    plt.hist(Z) 
    plt.title("Exponential Frequency Histogram") 
    plt.show() 
    return Z[:10] #Show only the first 10 values of the list. 

在第一功能,我計算可變X並且在第二I找到Z基於X並繪製其直方圖。我無法理解如何將變量X傳遞給第二個函數。我運行下面的第一個功能:

LCM(27, 17, 9, 10000, 10000) 

,這第二:

exponential(10) 

我也知道我可以使用一些軟件包,使這些東西(LCM隨機生成和EXP頗)但是,我想做一些練習。

+1

您需要使用'global'關鍵字在第一個函數中創建變量X global。即在編寫X = [] – skilledDt

+0

之前在第一個函數內的第一行寫入全局X.要理解正在進行的操作,可能需要閱讀Python中變量的範圍。文檔中有很多教程,但[此解釋](http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html)相當不錯。 – Bill

+1

@Bill,我喜歡教程中的[9.1和9.2](https://docs.python.org/3/tutorial/classes.html#a-word-about-names-and-objects)和[4.2命名和Binding](https://docs.python.org/3/reference/executionmodel.html#naming-and-binding)語言參考 – wwii

回答

4

既然你正在返回從第一功能的X值,你可以將它們傳遞到第二功能如下:

X = LCM(27, 17, 9, 10000, 10000) 
Z = exponential(X, 10) 

你只需要一個參數添加到exponential爲X的值。

+0

'你只需要添加...'參數。 – wwii

+0

謝謝@wwii。我只是[學到了一些東西](https://docs.python.org/3/faq/programming.html#faq-argument-vs-parameter)。 – Bill

0

您需要從LCM函數返回的值傳遞到一個變量,所以你做 -

x = lcm(27, 17, 9, 10000, 10000) 

然後你通過x的值作爲參數傳遞到指數函數爲 -

x = exponential(10) 

另一種方法是你可以在你的函數之外聲明一個全局變量X = [],並且你可以在你的兩個函數中使用它們。沒有把它作爲第二個參數。

0

您可以通過聲明爲在分配給它的每個功能的全球使用其他功能的全局變量:

x = 0 
def f(): 
    x = 1 
f() 
print x #=>0 

,並期望1.相反,你需要做的聲明,你打算使用全局x:

x = 0 
def f(): 
    global x 
    x = 1 
f() 
print x #=>1 

我希望它能幫到你。或者至少讓你更接近解決方案。

相關問題