Writting Code for newtons method

조회 수: 8 (최근 30일)
Emmanuel Pardo-Cerezo
Emmanuel Pardo-Cerezo 2019년 9월 24일
댓글: Rik 2019년 9월 24일
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
Jim Riggs
Jim Riggs 2019년 9월 24일
편집: Jim Riggs 2019년 9월 24일
I'm guessing that he wants you to compare the bisection method with Newton's method.
E.g. which one converges faster?
Rik
Rik 2019년 9월 24일
@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.

댓글을 달려면 로그인하십시오.

답변 (1개)

David Hill
David Hill 2019년 9월 24일
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)

카테고리

Help CenterFile Exchange에서 Systems of Nonlinear Equations에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by