WID3004 Assignment 1
AMIRUL ZHARFAN BIN ZALID - 17194420/1
def bisect(func, sign, low, high, e=None, i=50):
assert not sign(func(low), func(high))
for i in range(i):
mp = (low + high) / 2.0
if sign(func(low), func(mp)):
low = mp
else:
high = mp
if e is not None and abs(high - low) < e:
break
return mp
def ss(a, b):
return b - a < 0
def f(x):
return x**6 - x - 1
bisect(f,ss,1,2,e=0.01,i=100)
def secant(func, x1, x2, e):
i=0
xm1 = 0
xm2 = 0
check = 0
if(func(x1) *func(x2) < 0):
while(1):
xm1 = (x1 * func(x2) - x2 * func(x1)) / (func(x2) - func(x1))
check = func(x1) * func(xm1)
if(check == 0):
break
x1 = x2
x2 = xm1
i = i + 1
if(func(x2) - func(x1) == 0):
xm2 = (x1 * func(x2) - x2 * func(x1)) / e
else:
xm2 = (x1 * func(x2) - x2 * func(x1)) / (func(x2) - func(x1))
if(abs(xm2 - xm1) < e):
break
return xm1
else:
return -1
def q4Func(x):
return x**4 - 5
print(secant(q4Func, 0, 0, 0))
print(secant(q4Func, 5**(1.0/4.0), 1.5, 0.01))
-1
1.4953487812212205
import math
def q5Func(x):
return math.e**x - (2-x)**3
secant(q5Func, 0, 5, 0.001)
from pprint import pprint
from numpy import array, zeros, diag, diagflat, dot, linalg, inf, double, zeros_like
A = array([[3, 12, 0, -1, 0, 0], [4, 0, 31, 1, 0, 0], [2, 1, 0, 0, 17, -3], [27, 2, 0, 0, 0, 1], [0, 0, 0, -1, 1, 11], [0, 0, 0, 24, -1, 0]])
b = array([39, 117, 12, 98, 14, 55])
guess = array([0,0,0,0,0,0])
def jacobi(A,b,N=25,x=None, e=0):
if x is None:
x = zeros(len(A[0]))
D = diag(A)
R = A - diagflat(D)
for i in range(N):
if(D.all() == 0):
x = (b - dot(R,x)) / e
else:
x = (b - dot(R,x)) / D
return x
sol = jacobi(A,b,N=25,x=guess, e=0.01)
print("A:")
print(A)
print("b:")
print(b)
print("x:")
print(sol)
A:
[[ 3 12 0 -1 0 0]
[ 4 0 31 1 0 0]
[ 2 1 0 0 17 -3]
[27 2 0 0 0 1]
[ 0 0 0 -1 1 11]
[ 0 0 0 24 -1 0]]
b:
[ 39 117 12 98 14 55]
x:
[-3.69622132e+81 6.58253121e+82 6.95608762e+81 4.19673730e+82
2.38728753e+82 2.65230395e+82]
def gauss_seidel(A, b, e=0, max_iterations=10000):
x = zeros_like(b, dtype=double)
for k in range(max_iterations):
x_old = x.copy()
for i in range(A.shape[0]):
x[i] = (b[i] - dot(A[i,:i], x[:i]) - dot(A[i,(i+1):], x_old[(i+1):])) / A[i ,i]
if linalg.norm(x - x_old, ord=inf) / linalg.norm(x, ord=inf) < e:
break
return x
A = array([[5, -2, -1, 1], [-2, 4, 1, 0], [1, 2, 6, -1], [-1, 0, 1, 6]])
b = array([6, 0, 6, -14])
print(gauss_seidel(A, b, e=0))
[ 2. 1. 0. -2.]