newtons method using function

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 个)

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

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by