newtons method using function

조회 수: 14 (최근 30일)
Catherine Chen
Catherine Chen 2020년 2월 29일
답변: David Hill 2020년 2월 29일
I have been testing the code but it does not seem right. could you please tell me where the issue occurs and how to correct it?
tnx.
function [x1] = tutorial1(x0,nMax,tol)
% Calculate the root of the function f(x) = x^3 - 3^x + 1
% using the Newton Method of root-finding.
% Inputs:
% - x0 initial guess
% - nMax number of iterations
% - tol solution accuracy tolerance
% Output:
% - x1 converged root of the equation
x0 = 1.5;
nMax = 15;
tol = 1e-4;
for i = 1 : nMax
fx= (x0)^3-3^(x0)+1;
df= 3*(x0)^2-3*(x0)*log(3);
x1 = x0 - fx/df;
fx1 = (x1)^3-3^(x1)+1;
err = abs(fx1-fx);
if err < tol
break
end
end
% Sample output code for monitoring (this should be included in your loop structure.
fprintf('Iteration = %d, x0 = %.4f, x1 = %.4f, fx1 = %.4f\n',i,x0,x1,fx1);
return

답변 (1개)

David Hill
David Hill 2020년 2월 29일
function x = tutorial1(x,nMax,tol)%it would be easier if everything was just x
f=@(x)x^3-3^x+1;%should place functions outside your loop
df=@(x)3*x^2-3;%not sure why your equation had a log(3)
for i = 1 : nMax
x = x - f(x)/df(x);
fprintf('Iteration = %d, x1 = %.4f, f(x) = %.4f\n',i,x,f(x));
if abs(f(x)) < tol%I assume you are measuring error with respect to the zero root
return;
end
end

카테고리

Help CenterFile Exchange에서 App Building에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by