我正在嘗試求解 T(p,q) 的方程,如附圖中更清楚地顯示。
在哪里:
- p = 0.60
- q = 0.45
- M - 3 行 6 列的系數矩陣
我創建了五個矩陣并將它們放在自己的函式中,以便稍后在 while 回圈中呼叫它們。但是,回圈不會遍歷 i 的各種值。
我怎樣才能讓回圈作業,或者有另一種/更好的方法可以解決以下方程嗎?

(僅供參考,這大約是我使用 Python 和編碼的第三天)
import numpy as np
def M1(i):
M = np.array([[1,3,0,4,0,0],[3,3,1,4,0,0],[4,4,0,3,1,0]])
return M[i-1,0]
def M2(i):
M = np.array([[1,3,0,4,0,0],[3,3,1,4,0,0],[4,4,0,3,1,0]])
return M[i-1,1]
def M3(i):
M = np.array([[1,3,0,4,0,0],[3,3,1,4,0,0],[4,4,0,3,1,0]])
return M[i-1,2]
def M4(i):
M = np.array([[1,3,0,4,0,0],[3,3,1,4,0,0],[4,4,0,3,1,0]])
return M[i-1,3]
def M5(i):
M = np.array([[1,3,0,4,0,0],[3,3,1,4,0,0],[4,4,0,3,1,0]])
return M[i-1,4]
def T(p,q):
sum_i = 0
i = 1
while i <=5:
sum_i = sum_i ((M1(i)*p**M2(i))*((1-p)**M3(i))*(q**M4(i))*((1-q)**M5(i)))
i = i 1
return sum_i
print(T(0.6,0.45))
"""I printed the below equation (using a single value for i) to test if the above loop is working and since I get the same answer as the loop, I can see that the loop is not cycling through the various values of i as expected"""
i=1
p=0.6
q=0.45
print(((M1(i)*p**M2(i))*((1-p)**M3(i))*(q**M4(i))*((1-q)**M5(i))))
uj5u.com熱心網友回復:
return 放在while回圈里面,你需要稍微修改一下代碼
while i <=5:
sum_i = sum_i ((M1(i)*p**M2(i))*((1-p)**M3(i))*(q**M4(i))*((1-q)**M5(i)))
i = i 1
return sum_i
uj5u.com熱心網友回復:
numpy 的真正力量是查看這些計算并嘗試了解什么是可重復的以及它們具有什么結構。一旦您找到相似或并行的操作,請嘗試設定您的 numpy 函式呼叫,以便它們可以在一次呼叫中并行地按元素完成。
例如,在和的典型元素中,有四件事被明確地提升為冪(如果考慮 M(i, 1)^1,則為五分之一)。在一次函式呼叫中,如果您巧妙地安排陣列,則可以在一次函式呼叫中并行執行所有四個冪運算:
M = np.array([[1,3,0,4,0,0],[3,3,1,4,0,0],[4,4,0,3,1,0]])
ps_and_qs = np.array([[p, (1-p), q, (1-q)]])
a = np.power(ps_and_qs, M[:,1:5])
現在a將填充一個 3 x 4 矩陣,其中包含所有指數。
現在下一步是如何減少這些。numpy 中內置了幾個歸約函式,它們在可能的情況下通過矢量化回圈有效地實作。它們可以大大加快您的代碼速度。特別是,既有product減少也有sum減少。對于您的等式,我們需要首先跨行相乘以獲得每行一個數字,然后對剩余的列求和,如下所示:
b = M[:,:1] * np.product(a,axis=1)
c = np.sum(b, axis=0)
c現在應該是一個等于在T評估的標量(p,q)。第三天需要考慮很多,但是如果您繼續使用 numpy 對需要更好性能的大型專案進行數值分析,則需要考慮一些事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/339623.html
下一篇:比較和過濾來自多個陣列的資料
