def gs_iter(x_0, epsilon, max_iter): # 2a A = np.matrix([[1.0, 1.0/2, 1.0/3], [1.0/2, 1.0, 1.0/4], [1.0/3, 1.0/4, 1.0]]) B = np.array([.1, .1, .1]).reshape(3, 1) S_inv = np.zeros((3, 3)) a, b, c, d, e, f = A[0, 0], A[1, 0], A[1, 1], A[2, 0], A[2, 1], A[2, 2] S_inv[0, 0] = 1.0/a S_inv[1, 0] = -b/(a*c) S_inv[1, 1] = 1.0/c S_inv[2, 0] = (-c*d+b*e)/(a*c*f) S_inv[2, 1] = -e/(c*f) S_inv[2, 2] = 1.0/f S = np.tril(A) U = A - S iteration = 0 error = 1000 x_n = x_0 while iteration < max_iter: x_1 = pascal.mult(pascal.mult(S_inv, -U), x_n) x_1 += pascal.mult(S_inv, B) error = pascal.norm_inf(x_1 - x_n) x_n = x_1 if epsilon > error: return x_n, iteration iteration += 1 else: return None, None
def jacobi_iter(x_0, epsilon, max_iter): # 2a A = np.matrix([[1.0, 1.0/2, 1.0/3], [1.0/2, 1.0, 1.0/4], [1.0/3, 1.0/4, 1.0]]) b = np.array([.1, .1, .1]).reshape(3, 1) iteration = 0 error = 1000 x_n = x_0 while iteration < max_iter: d = np.diag(1 / np.diag(A)) alu = A - np.diag(np.diag(A)) x_1 = pascal.mult(d, b) + pascal.mult(pascal.mult(d, -alu), x_n) error = pascal.norm_inf(x_1 - x_n) x_n = x_1 if epsilon > error: return x_n, iteration iteration += 1 else: return None, None
jacobi, gs = iterative.generate_data() j_vals = [i[1] for i in jacobi] g_vals = [i[1] for i in gs] jacobi_approx = sum(j_vals) / len(j_vals) # 2c gs_approx = sum(g_vals) / len(g_vals) print("Averages, jacobi then gauss-seidel, then iterations") print(jacobi_approx) print(gs_approx) print(float(sum(j[2] for j in jacobi))/sum(g[2] for g in gs)) exact = np.array([9.0/190, 28.0/475, 33.0/475]).reshape(3,1) errs_jacobi = [pascal.norm_inf(j-exact) for j in j_vals] errs_gs = [pascal.norm_inf(g-exact) for g in g_vals] plt.plot([j[2] for j in jacobi], errs_jacobi, 'ko', [g[2] for g in gs], errs_jacobi, 'bo') plt.savefig('./iterative_err.png') plt.clf() powers = power.generate_data() ds = [p[0] for p in powers if p[0] is not None] ts = [p[1] for p in powers if p[1] is not None] tis = [p[2] for p in powers if p[2] is not None] maxs = [p[3] for p in powers if p[3] is not None] mins = [p[4] for p in powers if p[4] is not None] big = max(maxs) small = max(mins)