Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

import numpy as np

import math

# Actual solution
def actual_sol(n):
x = np.zeros(n)
for i in range(n):
x[i] = (i/2) + (-n/4)
return x

def gauss_siedel(A, b, t, w):


x = np.zeros_like(b, dtype=np.double)
condition = True
iter = 0
while condition:

# x_prev = x.copy()

R_rms = 0

for i in range(A.shape[0]):
R = (b[i]-np.dot(A[i,:], x[:]))
x[i] = w*(R/A[i,i]) + x[i]
R_rms = R_rms + R**2
R_rms = math.sqrt(R_rms/A.shape[0])
# print(R_rms)
# print("\n")

if R_rms <=t:
condition = False
iter +=1
return (x, iter, R_rms)

def main():
n = int(input())
A = np.zeros([n,n])
diag = int(input())
A[0][0] = diag
A[0][1] = -1
A[0][-1] = 1

for i in range(1, n):


A[i,1:] = A[i-1, :-1]
if A[i-1, -1] != 0:
A[i, 0] = -A[i-1, -1]

b = np.zeros(n)
b[-1] = 1
# print(A)
# print(b)
t = 1e-6
w = float(input())
x, iter, R_rms = gauss_siedel(A, b, t, w)
print(f"Convergence after {iter} iterations")
print("R_rms value: ", R_rms)
print(x)
print("\n")
print("Actual Solution: ", actual_sol(n))
print("Error between iterative solution and actual solution: ", (abs(sum(x)-
sum(actual_sol(n))))/abs(sum(actual_sol(n))))

You might also like