将停止条件添加到Jacobi方法

时间:2018-09-13 11:01:22

标签: python loops

我想做的是向我的Jacobi程序添加一个停止条件。该停止条件查看先前的迭代值,并将其与当前值进行比较。如果矩阵值已经收敛,则迭代中断。如果不是,则继续。

因此,我们将阈值设置为0.00001。如何确定值是否收敛,从而打破循环?

我的猜测是,如果current / m [v,v] <= 0.00001,那么我会打破循环...

def jacobi(m,numiter=100,e=0.00001):

    # Number of rows determins the number of variables
    numvars = m.shape[0]

    # construct array for final iterations
    history = np.zeros((numvars,numiter))
    i = 1
    while(i < numiter): #Loop for numiter

        for v in range(numvars): # Loop over all variables
            current = m[v,numvars] # Start with left hand side
            for col in range(numvars): #Loop over columns
                if v != col: # Don't count colume for current variable
                    current = current - (m[v,col]*history[col, i-1]) 
            current = current/m[v,v] #divide by current variable coefficent

            history[v,i] = current #Add this answer to the rest
        i = i + 1 #iterate

    #plot each variable
    for v in range(numvars):
        plt.plot(history[v,: i]);
    return history[:,i-1]

0 个答案:

没有答案