在python中更改输出语句

时间:2018-10-23 00:47:43

标签: python

我创建了以下代码。除了我的输出语句,一切都正确。在x:数组的末尾有一个79,代表迭代次数。我正在尝试发表使用

的声明
MongooseError: If you are populating a virtual, you must set the localField and foreignField options

我试图将iter_ct放在那里,但它给了我一个错误。寻求有关此调整的帮助,谢谢!     将numpy导入为np     从pprint导入pprint     从numpy导入数组,零,diag,diagflat,点

print("The number of iterations is", )

这是我现在得到的当前输出。注意x:数组

末尾的79
def jacobi(A,b,N=100,x=None):
    """Solves the equation Ax=b via the Jacobi iterative method."""
    # Create an initial guess if needed                                                                       
    if x is None:
        x = zeros(len(A[0]))

    # Create a vector of the diagonal elements of A                                                                                                                                                
    # and subtract them from A                                                                                                                                                                     
    D = diag(A)
    R = A - diagflat(D)

    x_old = x
    error = 1.0     # Dummy value
    iter_ct = 0
    while error > 10 ** (-15):
        x = (b - dot(R, x_old)) / D
        error = np.linalg.norm(x - x_old)
        iter_ct += 1
        x_old = x
    return x, iter_ct

A = np.array([[3.0, 1.0, 0., 0., 0., 0., 0., 0., 0., 0.],[1.0, 3.0, 1.0, 0., 0., 0., 0., 0., 0., 0.], [0., 1.0, 3.0, 1.0, 0., 0., 0., 0., 0., 0.], [0., 0, 1.0, 3.0, 1.0, 0., 0., 0., 0., 0.], [0., 0., 0., 1.0, 3.0, 1.0, 0., 0., 0., 0.], [0., 0., 0., 0., 1.0, 3.0, 1.0, 0., 0., 0.], [0., 0., 0., 0., 0., 1.0, 3.0, 1.0, 0., 0.], [0., 0., 0., 0., 0., 0., 1.0, 3.0, 1.0, 0.], [0., 0., 0., 0., 0., 0., 0., 1.0, 3.0, 1.0], [0., 0., 0., 0., 0., 0., 0., 0., 1.0, 3.0]])
b = np.array([1.0,1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
guess = np.array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

sol, iter = jacobi(A,b,N=100,x=guess)

print ("A:")
pprint(A)

print ("b:")
pprint(b)

print ("x:")
pprint(sol)

print("It took",sol[1], "iterations.")

3 个答案:

答案 0 :(得分:1)

您正在从jacobi函数-return x, iter_ct返回两个值。这已分配给sol

也许您可以尝试:

sol, iter = jacobi(A,b,N=100,x=guess)
pprint(sol)
#pprint(iter)  - don't print the '79'

答案 1 :(得分:1)

您的jacobi函数返回一个元组(x, iter_ct),因此,如果您只想打印iter_ct,可以这样做:pprint(sol[1])

或者,您可以在返回元组时将其拆包:

sol, iter = jacobi(A,b,N=100,x=guess)
pprint(iter)

答案 2 :(得分:1)

print("The number of iterations is {}".format(x[-1]))

执行函数后,使用上面的语句。