我有以下函數來計算兩個不同的東西:在另一個函數使用函數的變量
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頗)但是,我想做一些練習。
您需要使用'global'關鍵字在第一個函數中創建變量X global。即在編寫X = [] – skilledDt
之前在第一個函數內的第一行寫入全局X.要理解正在進行的操作,可能需要閱讀Python中變量的範圍。文檔中有很多教程,但[此解釋](http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html)相當不錯。 – Bill
@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