Write a series of tests for Newton\'s Method (attached below) that verifies that
ID: 3282467 • Letter: W
Question
Write a series of tests for Newton's Method (attached below) that verifies that the function produces the correct value with the indicated inputs:
input: (@(x) x.^2 -2,@(x) 2*x,1)
output: sqrt(2)
input: (@(x) x.^2 -2,@(x) 2*x,-1)
output: -sqrt(2)
input: (@(x) x.^2 - sin(x), 2*x - cos(x),1)
output: 0.8767262153950624
You may have to set a tolerance for the error instead of just using verifyEqual
Also: add a special error message to Newton's Method that triggers when the derivative is too close to zero (say 1e-8), where the program stops.
Add a test that checks for this error.
Explanation / Answer
function dummy=Newtonm()
clc;
clear all;
f=@(x)x^2-2;%function
f1=@(x)2*x; %derivative of function
x0=1;%initial guess
y1=Newton(f,f1,x0)
x01=-1;
y1=Newton(f,f1,x01)
f2=@(x)x^2-sin(x);
f21=@(x)2*x-cos(x)
x02=1;
y1=Newton(f2,f21,x02)
function y1=Newton(f,f1,x0)
n=1;
erorr=0.1;
del=1e-10;
x(1)=x0;
while (abs(erorr>del))
y1=x0-(f(x0)/f1(x0));% Newton method
erorr(n+1)=abs((y1-x0)); %erorr
if abs(erorr<1e-3)
break
end
x0=y1; % update xold
x(n+1)=x0;
n=1+n;
end
if (n<100)
disp('Root is')
x(end)
disp('num_iter x_value erorr')
disp('_______________________________________________________________________________')
for i=1:n-1
fprintf('%d %20f %20f ',i ,x(i),erorr(i))
end
else
fprintf('The required accuracy is not reached in 100 iteration')
end
end
end
%%%% Solution %%%%%
Root is
ans =
1.414213562373095
num_iter x_value erorr
_______________________________________________________________________________
1 1.000000 0.100000
2 1.500000 0.500000
3 1.416667 0.083333
4 1.414216 0.002451
5 1.414214 0.000002
y1 =
1.414213562373095
Root is
ans =
-1.414213562373095
num_iter x_value erorr
_______________________________________________________________________________
1 -1.000000 0.100000
2 -1.500000 0.500000
3 -1.416667 0.083333
4 -1.414216 0.002451
5 -1.414214 0.000002
y1 =
-1.414213562373095
f21 =
@(x)2*x-cos(x)
Root is
ans =
0.876726215395063
num_iter x_value erorr
_______________________________________________________________________________
1 1.000000 0.100000
2 0.891396 0.108604
3 0.876985 0.014411
4 0.876726 0.000259
5 0.876726 0.000000
y1 =
0.876726215395063
>>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.