what should we do in matlab code for newtons raphson method in the case f'(xn)=0 ?

2 views (last 30 days)
This code doesnot work if f'(xn)=0 in some iteration so what should be the general code for Newtons raphson method?

Answers (1)

Maneet Kaur Bagga
Maneet Kaur Bagga on 7 Oct 2024
Edited: Maneet Kaur Bagga on 7 Oct 2024
Hi,
As per my understanding from the given code, following are the errors which can cause runtime errors:
  1. When using the Newton Raphson method if the derviative "f'(xn) = 0" at any iteration, the algorithm will attempt to divide the expression by zero leading to a runtime error.
  2. If the derivative is zero, the while loop would become infinite as the "err" variable will never decrease.
  3. If the function value "f(x(i+1)) is exactly zero, it breaks the loop without reporting about convergence or the number of iterations taken.
  4. The convergence check is based on the error between iterations. You can add a check for the function value approaching zero to indicate of the method is convergin to the root.
To overcome the above edge cases you can check if the derivative is zero before computing the next approximation. Also, you can add a small pertubation to the point if the derivative is very close to zero to avoid division by zero.
Please refer to the modified code below for better understanding:
format long
f = @(x) x^3 - 2*x - 5;
f1 = @(x) 3*x^2 - 2;
tol = 0.001;
i = 1;
x(i) = 2;
err = 1;
while err >= tol
% Calculate the derivative at the current point
derivative = f1(x(i));
% Check if the derivative is close to zero
if abs(derivative) < 1e-10 % Adjust tolerance as needed
disp('Derivative is zero or very close to zero. Switching method or adjusting guess.')
% Option 1: Adjust the guess slightly (perturbation)
x(i) = x(i) + 1e-6; % Small perturbation
derivative = f1(x(i)); % Recalculate derivative after perturbation
end
% Newton-Raphson formula
x(i+1) = x(i) - (f(x(i)) / derivative);
err = abs(x(i+1) - x(i));
% Check for exact root
if f(x(i+1)) == 0
break;
end
i = i + 1;
end
% Display the result
fprintf('Root found: %f\n', x(end));
fprintf('Function value at root: %f\n', f(x(end)));
fprintf('Number of iterations: %d\n', i);
I hope this helps!

Products


Release

R2014a

Community Treasure Hunt

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

Start Hunting!