Writting Code for newtons method
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
The professor asked us the following problems:
PROBLEM1. The function f(x)=sin(x) has a zero on the interval (3,4), namely, x*=pi. Perform three iterations of newton mathod to aproxximate this zero, using x1=4. Determine the absolute error in each of the computed approximations. What is the apparent order of convergence?
PROBLEM2. Apply the Newton Method to find the solution to (x^3)-x-3=0 starting with x1=0. COmpute x2, x3, x4,x5,x6,x7 and x8 compare numbers (x1,x5), (x2,x6), (x3,x7), (x4,x8). What can you conclude from this computations (use your computer code)?
he have us the following code:
% Sept/2016
%
% Solve f(x) = 0 using bisection method.
%
% The function is defined in func(x);
% Input
tol = 1.e-10;
a = 1.0;
b = 2.0;
nmax = 100;
% Initialization
itcount = 0;
error = 1.0;
% Graph of the function
xval = linspace(a,b,100);
for i=1:100
fval(i) = func(xval(i));
end plot(xval,fval);
grid on;
hold on;
% iteration begins here
while (itcount <= nmax && error >= tol)
itcount = itcount + 1;
% Generate and save iteratres
x = a + (b-a)/2;
z(itcount) = x;
fa = func(a);
fb = func(b);
fx = func(x);
error = abs(fx);
% error = abs(x - xold);
if (error < tol)
x_final = x;
else
if (fa*fx < 0)
% root is between a and x
b = x;
else
% root is between x and b
a = x;
end
end
plot(z(1:itcount),zeros(itcount,1),'r+');
pause(5)
end
if (itcount < nmax);
val = func(x);
fprintf(1,'Converged solution after %5d iterations',itcount);
fprintf(1,' is %15.7e, %e \n',x_final, val);
else
fprintf(1,'Not converged after %5d iterations',nmax);
end
function val = func(x)
%val = x^3 + 4 * x^2 - 10;
val = x^3 - x - 3;
%val = sin(x);
end
3 comentarios
Rik
el 24 de Sept. de 2019
@Emmanuel: The point is: it is unclear what your question is and what you have tried so far on your own to solve this homework question.
Respuestas (1)
David Hill
el 24 de Sept. de 2019
f=@sin;
fp=@cos;
function x = newtonMethod(f,fp,x,i)
for j=1:i
er=-f(x)/fp(x);
x=x+er;
end
end
x=newtonMethod(f,fp,4,3);
Then just change functions and call the newtonMethod again.
f=@(x)x^3-x-3;
fp=@(x)3*x^2-1;
x=newtonMethod(f,fp,0,8)
0 comentarios
Ver también
Categorías
Más información sobre Systems of Nonlinear Equations en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!