Part 7. Metode Jacobi dan Metode Gauss-Seidel



Berikut saya sapaikan metode Jacobi dan Metode Gauss-Seidel untuk menyelesaikan n persamaan, dengan n bilangan anu secara iteratif.

Metode Jacobi

import numpy as np

# Define the matrix A and vector b

A = np.array([[5, -1, 1, 2], [2, 7, -1, -2], [2, -3, 8, 1], [7, -3, 1, 9]])

b = np.array([-4, 3, 1, 12])

# Solve the system of equations A*x = b

xx = np.linalg.solve(A, b)

# Print the solution

print("xx =")

print(xx)

# Iterative process

n = 4

w, x, y, z = 0, 0, 0, 0

 

print("\nIterative refinement:")

print("iter     w1         x1        y1       z1")

 

for i in range(1, 21):

    w1 = (b[0] - (x*A[0,1]) - y*A[0,2] - z*A[0,3]) / A[0,0]

    x1 = (b[1] - w*A[1,0] - y*A[1,2] - z*A[1,3]) / A[1,1]

    y1 = (b[2] - w*A[2,0] - x*A[2,1] - z*A[2,3]) / A[2,2]

    z1 = (b[3] - w*A[3,0] - x*A[3,1] - y*A[3,2]) / A[3,3]

   

    print(f"{i:4d} {w1:10f} {x1:10f} {y1:10f} {z1:10f}")

   

    # Check for convergence

    if np.abs(w1-w) < 0.0001 and np.abs(x1-x) < 0.0001 and np.abs(y1-y) < 0.0001 and np.abs(z1-z) < 0.0001:

        break

    w, x, y, z = w1, x1, y1, z1

 

Metode Gauss-Seidel

import numpy as np

# Define the matrix A and vector b

A = np.array([[5, -1, 1, 2], [2, 7, -1, -2], [2, -3, 8, 1], [7, -3, 1, 9]])

b = np.array([-4, 3, 1, 12])

# Solve the system of equations A*x = b

xx = np.linalg.solve(A, b)

print("xx =")

print(xx)

# Initial guesses for the solution

w = x = y = z = 0

print("\nIterative process:")

 

# Store the iteration results

table = []

 

for i in range(1, 21):

    w_old, x_old, y_old, z_old = w, x, y, z  # Store old values for convergence check

   

    w = (b[0] - (x*A[0,1]) - y*A[0,2] - z*A[0,3]) / A[0,0]

    x = (b[1] - w*A[1,0] - y*A[1,2] - z*A[1,3]) / A[1,1]

    y = (b[2] - w*A[2,0] - x*A[2,1] - z*A[2,3]) / A[2,2]

    z = (b[3] - w*A[3,0] - x*A[3,1] - y*A[3,2]) / A[3,3]

   

    # Save the iteration results

    table.append([i, w, x, y, z])

 

    # Check for convergence

    if np.allclose([w_old, x_old, y_old, z_old], [w, x, y, z], atol=0.0001):

        break

 

# Print the results

print("     iter     w         x        y       z")

for row in table:

    print(f"{row[0]:5d} {row[1]:10f} {row[2]:10f} {row[3]:10f} {row[4]:10f}")

 

 

Post a Comment

0 Comments