My Newton Raphson Script Stucks at first step
Show older comments
clc
a = input('Enter initial guess: ');
e = input('Tolerable error: ');
N = input('Enter maximum number of steps: ');
step = 1;
g = diff(f(x));
while abs(f(a))> e
if g(a) == 0
disp('Division by zero.');
break;
end
b = a - f(a)/g(a);
fprintf('step=%d\ta=%f\tf(a)=%f\n',step,a,f(a));
a = b;
if step>N
disp('Not convergent');
break;
end
step = step + 1;
end
fprintf('Root is %f\n', a);
I have function file called f.m . It consists:
function f= f(x)
f=cos(x)-x.*exp(x);
end
When I run it it stucks at first. It doesn't do other iterations. How can I figure it out? I need to have separate function file and call it like this.
Answers (1)
a = 1.0;
e = 1e-6;
N = 30;
syms x
fsym = cos(x)-x*exp(x);
f = matlabFunction(fsym);
g = matlabFunction(diff(fsym,x));
step = 1;
%g = diff(f(x));
while abs(f(a))> e
if g(a) == 0
disp('Division by zero.');
break;
end
b = a - f(a)/g(a);
fprintf('step=%d\ta=%f\tf(a)=%f\n',step,a,f(a));
a = b;
if step>N
disp('Not convergent');
break;
end
step = step + 1;
end
fprintf('Root is %f\n', a);
2 Comments
st0s
on 28 Mar 2022
Then you must define f(x) twice:
syms x
fsym = cos(x)-x*exp(x);
g = matlabFunction(diff(fsym,x));
...
function value = f(x)
value = cos(x)-x*exp(x);
end
Or you define f as a function handle and not as a function:
f = @(x) cos(x)-x*exp(x);
g = eval(['@(x)' char(diff(f(x)))])
%or vectorized:
g = eval(['@(x)' vectorize(char(diff(f(x))))])
Or you calculate g = f'(x) using paper and pencil (my suggestion).
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!