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.

 채택된 답변

John D'Errico
John D'Errico 2017년 5월 20일

1 개 추천

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

Joseph Achou
Joseph Achou 2020년 3월 21일
Is there a way to generalize this code andd make it into a function?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 5월 20일

댓글:

2020년 3월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by