系数矩阵和循环挑战

Coefficient matrix and loops challenge

我正在尝试求解 T(p,q) 的方程,如附图中更清楚地显示的那样。

其中:

我创建了五个矩阵并将它们放在各自的函数中,以便稍后在 while 循环中调用它们。但是,循环不会循环遍历 i.

的各种值

我怎样才能让循环工作或者有什么方法可以another/better解下面的方程?

(仅供参考,这大约是我使用 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))))

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

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 对需要更好性能的更大项目进行数值分析,则需要考虑一些事情。