[Python] Jacobi Method on Python stopping at 3rd iteration [closed]

Discussão em 'Python' iniciado por Stack, Novembro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to code a jacobi algorithm w/o using matrices on python. The code I came up with looks fine but it stops at 3rd iteration even though the error is still pretty much large.

    ps. I am not an experienced programmer. I'm only doing this because this is one of our projects for an engineering course.

    from sympy import *
    import numpy as np
    f = Function('f')
    x, y, z = symbols('x y z')
    print("*note: Transpose the right hand side of the equation and do not use '=' signs")
    #Equation 1
    inputEq1 = input("Input Eq 1 [f(x,y,z)]: ")
    eq1 = sympify(inputEq1)
    solvedEq1 = solve(eq1, x)
    print(solvedEq1)
    def gx(n,m):
    fx = lambdify((y,z), solvedEq1, 'numpy')
    return fx(n,m)

    #Equation 2
    inputEq2 = input("Input Eq 2 [f(x,y,z)]: ")
    eq2 = sympify(inputEq2)
    solvedEq2 = solve(eq2, y)
    print(solvedEq2)
    def gy(n,m):
    fy = lambdify((x,z), solvedEq2, 'numpy')
    return fy(n,m)

    #Equation 3
    inputEq3 = input("Input Eq 3 [f(x,y,z)]: ")
    eq3 = sympify(inputEq3)
    solvedEq3 = solve(eq3, z)
    print(solvedEq3)
    def gz(n,m):
    fz = lambdify((x,y), solvedEq3, 'numpy')
    return fz(n,m)
    #initial guesses
    xinitial = float(input("Input initial guess (xi): "))
    yinitial = float(input("Input initial guess (yi): "))
    zinitial = float(input("Input initial guess (zi): "))

    def convList(lst):
    result =''
    for i in lst:
    result += str(i)
    return float(result)
    #Jacobi Algorithm
    def jacobiMethod(gx, gy, gz, x, y, z, convList, erx = 2.2250738585072014e-308, ery = 2.2250738585072014e-308, erz = 2.2250738585072014e-308, maxiteration=1000):
    xi = x
    yi = y
    zi = z
    errorx = 100000
    errory = 100000
    errorz = 100000
    k = 0
    print("Iterations: ", k, ", x= ", xi, ", y= ", yi, ", z= ", zi, ", errorx: ", errorx, ", errory: ", errory, ", errorz: ", errorz)
    while k<maxiteration and errorx>erx and errory>ery and errorz>erz:
    xnew = convList(gx(yi,zi))
    ynew = convList(gy(xi,zi))
    znew = convList(gz(xi,yi))
    errorx = abs(xnew - xi)
    xi = xnew
    errory = abs(ynew - yi)
    yi = ynew
    errorz = abs(znew - zi)
    zi = znew
    k = k+1
    print("Iterations: ", k, ", x= ", xi, ", y= ", yi, ", z= ", zi, ", xnew= ", xnew, ", ynew= ", ynew, ", znew= ", znew, ", errorx: ", errorx, ", errory: ", errory,
    ", errorz: ", errorz)
    return xi, yi, zi

    print(jacobiMethod(gx, gy, gz, xinitial, yinitial, zinitial, convList))

    Continue reading...

Compartilhe esta Página