如何为雅可比矩阵添加停止条件?

时间:2018-09-12 22:41:52

标签: python python-3.x

def jacobi(m,numiter=100):

    #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 (augmented side of matrix)
            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]) #subtract other guesses form previous timestep
            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]

我有这段代码可以计算Jacobian方法。当解决方案收敛时,如何添加停止条件?也就是说,当前迭代的值与前一次迭代的值相比变化幅度小于某个阈值e

阈值e将作为函数的输入,默认值为0.00001

1 个答案:

答案 0 :(得分:0)

您可以在while循环中添加另一个条件,因此当达到错误阈值时,它将停止。

def jacobi(m,numiter=100, error_threshold = 1e-4):

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

  #construct array for final iterations
  history = np.zeros((numvars,numiter))
  i = 1
  err = 10*error_threshold
  while(i < numiter and err > error_threshold): #Loop for numiter and error threshold

      for v in range(numvars): # Loop over all variables
          current = m[v,numvars] # Start with left hand side (augmented side of matrix)
          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]) #subtract other guesses form previous timestep
          current = current/m[v,v] #divide by current variable coefficent

          history[v,i] = current #Add this answer to the rest
      #check error here. In this case the maximum error
      if i > 1:
        err = max((history[:,i] - history[:,i-1])/history[:,i-1])

      i = i + 1 #iterate



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