Problem in code for Newton Raphson Method

if true
% code
function x = newton(x0)
tolerance = 10^(-8);
error = 999;
x = x0;
while error>tolerance
f = x-x^(1/3)-2; % Function value
dfdx = 1-(1/3)*x^(-2/3); % Derivative value
x = x-f/dfdx; % Newton-Raph Equation
error = abs(((x-x0)/x)*100);
x0 = x;
end
end
end
While executing this code I'm getting x = 0, which is not the intended answer. Please help.

 Réponse acceptée

John D'Errico
John D'Errico le 20 Mai 2017
It would seem that knowing what your starting value was would be of importance.
When I run that code, I get
x =
3.5214
But then, maybe my starting guess was more intelligently chosen than yours. So, plot your function. ALWAYS plot EVERYTHING. Think about what will happen if you give it some arbitrary starting point in x0. In fact, I wonder if you tried starting at x0=0. In hindsight, think about how Newton's method works. Then look at the plot. Do you think that 0 is a good choice here?
fun = @(x) x - nthroot(x,3) - 2;
ezplot(un,[-5,5])
grid on
Failing to carefully think about what you are doing tends to yield randomly poor results.
Finally, note that I used nthroot. It is a bit safer then x^(-1/3). In fact, I'd suggest that a better computational choice for x^(-2/3) may also be nthroot(x,3)^2. Why is that? What happens when x happens to be a negative number?
(-1)^(-1/3)
ans =
0.5 - 0.86603i
(-1)^(-2/3)
ans =
-0.5 - 0.86603i

1 commentaire

Joseph Achou
Joseph Achou le 21 Mar 2020
Is there a way to generalize this code andd make it into a function?

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by