Professional Documents
Culture Documents
import numpy as np
In [28]:
#Define Newton's method function for matrix that calculates the error with l2 no
rm
def NewtonsMethodFirstFixedPoint(x0, epsilon):
#Define f(x)
def f(x):
f = np.array([x[1] * np.sin(x[0]),
np.square(x[0]) + x[1] - x[2],
x[1] + x[2]])
return f
#Define the jacobian matrix
def jf(x):
df = np.array([[x[1] * np.cos(x[0]), np.sin(x[0]), 0],
[2*x[0], 1, -1],
[0, 1, 1]])
return df
#Initialize iteration
iterations = 0
#Initialize empty list for error
error_list1 = []
#Compute f(x) and Norm
fx0 = f(x0)
fn = np.linalg.norm(fx0, ord=2)
#While root not reached
while np.absolute(fn) > epsilon:
#It is computationally taxing to solve the Newton's Iteration Literally
#Can rewrite the equation into Ax = b form
solve = np.linalg.solve(jf(x0), -fx0)
x0 = x0 + solve
fx0 = f(x0)
fn = np.linalg.norm(fx0, ord=2)
#Update Iterations
iterations += 1
#Calculate error with respect to the first root
e = np.linalg.norm(x0 - np.array([0, 0, 0]), ord=1)
#Add to error list
error_list1.append(e)
#Print statements
print('In iteration ' + str(iterations) +', root is: ' + str(x0))
print('Error for iteration ' + str(iterations) + ' is:' + str(e))
print('Got the answer in iteration: ' + str(iterations))
print('Answer is: ' + str(x0))
return error_list1
In [33]:
Out[33]:
[0.11669146641349601,
0.07400707995839853,
0.0460590224353548,
0.02848260969179668,
0.01758008498739306,
0.010847786069145087,
0.006695229850316273,
0.004133697072816685,
0.0025529582116494125,
0.0015770635906698445,
0.0009743740889230849,
0.0006020746821576281,
0.0003720546476876564]
In [35]:
Out[35]:
[1.041426389145041,
1.0134803085988338,
1.0039469711145301,
1.0005776425391815,
0.9995028719133637,
0.9992901040952773,
0.9993701735778056,
0.9995201003379071,
0.9996604990039033,
0.9997699083734802,
0.9998482346503845]
x2 = [3, -3, 3]
NewtonsMethodSecondFixedPoint(x2, 0.000001)
Out[37]:
[0.4559868000778841,
0.01920194172363646,
4.577350895583193e-05,
2.7038521955124045e-10]
In [38]:
Out[38]:
[1.9065988362906567, 1.9935827869937885]
def LUDecomp(A):
#Initialize empty matrices
lower = np.eye(4)
upper = np.zeros((4,4))
#Size of n = 4
for i in range(4):
In [40]:
A = [[1.0,2.0,3.0,4.0],
[2.0,9.0,12.0,15.0],
[3.0,26.0,41.0,49.0],
[5.0,40.0,107.0,135.0]]
LUDecomp(A)
L : [[1. 0. 0. 0.]
[2. 1. 0. 0.]
[3. 4. 1. 0.]
[5. 6. 7. 1.]]
U : [[ 1. 2. 3. 4.]
[ 0. 5. 6. 7.]
[ 0. 0. 8. 9.]
[ 0. 0. 0. 10.]]
In [41]:
In [42]:
A = [[1.0,2.0,3.0,4.0],
[2.0,9.0,12.0,15.0],
[3.0,26.0,41.0,49.0],
[5.0,40.0,107.0,135.0]]
LUDecompn(A,4)
L : [[1. 0. 0. 0.]
[2. 1. 0. 0.]
[3. 4. 1. 0.]
[5. 6. 7. 1.]]
U : [[ 1. 2. 3. 4.]
[ 0. 5. 6. 7.]
[ 0. 0. 8. 9.]
[ 0. 0. 0. 10.]]
Problem 6 Backward Substitution
In [43]:
In [44]:
U = np.array([[1, 2, 6, -1],
[0, 3, 1, 0],
[0, 0, 4, -1],
[0, 0, 0, 2]])
b = np.array([-1, -3, -2, 4])
BackSub(U, b)
Out[44]: