MATLAB ASSIGNMENT CODE:
NEWTON RAPHSON AND SECANT METHOD
Question 1: Use (a) fixed-point iteration and (b) Newton Raphson method to
determine a root of f(x) = -x2 + 1.8x + 2.5 using x0 = 5. Perform the computation
until error is less than 0.05%. Also perform an error check of your final answer
Solution:
Fixed Point Iteration:
f = @(x) -x^2 + 1.8*x + 2.5
g = @(x) sqrt(1.8*x + 2.5);
x0 = 5
while true
x1 = g(x0)
error = abs((x1 - x0)/x1)
if error < 0.0005, break; end
x0 = x1
end
x1
error
Newton Raphson Method:
f = @(x) -x^2 + 1.8*x + 2.5
df = @(x) -2*x + 1.8;
x0 = 5
while true
x1 = x0 - f(x0)/df(x0)
error = abs ((x1 - x0)/x1)
if error < 0.0005, break; end
x0 = x1
end
x1
error
Output:
FPI:
x0 = 5
x1 = 3.3912
error = 0.4744
x0 = 3.3912
x1 = 2.9333
error = 0.1561
x0 = 2.9333
x1 = 2.7892
error = 0.051637
x0 = 2.7892
x1 = 2.7424
error = 0.017090
x0 = 2.7424
x1 = 2.7270
error = 5.6562e-03
x0 = 2.7270
x1 = 2.7219
error = 1.8720e-03
x0 = 2.7219
x1 = 2.7202
error = 6.1957e-04
x0 = 2.7202
x1 = 2.7196
error = 2.0505e-04
x1 = 2.7196
error = 2.0505e-04
NR:
x0 = 5
x1 = 3.3537
error = 0.4909
x0 = 3.3537
x1 = 2.8013
error = 0.1972
x0 = 2.8013
x1 = 2.7211
error = 0.029482
x0 = 2.7211
x1 = 2.7193
error = 6.4980e-04
x0 = 2.7193
x1 = 2.7193
error = 3.1555e-07
x1 = 2.7193
error = 3.1555e-07
Question 2: Determine the lowest real root of f(x) -12-21x+18x2-2.4x3 using the
Secant Method to an error value corresponding to three significant figures
Solution:
f = @(x) -12 - 21*x + 18*x.^2 - 2.4*x^3
x0 = -5
x1 = -3
tol = 0.0005
error = 1
while error > tol
x2 = x1 - f(x1)*(x1 - x0)/(f(x1) - f(x0))
error = abs((x2 - x1)/x2)
x0 = x1
x1 = x2
end
x2
error
Output:
tol = 5.0000e-04
error = 1
x2 = -2.0170
error = 0.4874
x0 = -3
x1 = -2.0170
x2 = -1.2327
error = 0.6362
x0 = -2.0170
x1 = -1.2327
x2 = -0.7702
error = 0.6006
x0 = -1.2327
x1 = -0.7702
x2 = -0.5225
error = 0.4738
x0 = -0.7702
x1 = -0.5225
x2 = -0.4331
error = 0.2065
x0 = -0.5225
x1 = -0.4331
x2 = -0.4164
error = 0.040218
x0 = -0.4331
x1 = -0.4164
x2 = -0.4154
error = 2.4246e-03
x0 = -0.4164
x1 = -0.4154
x2 = -0.4154
error = 2.4330e-05
x0 = -0.4154
x1 = -0.4154
x2 = -0.4154
error = 2.4330e-05