newton's method to solve nonlinear equation

2 views (last 30 days)
hw prompt is below my work. please check my code. i am new to using newton's method and need some recommendations about what to do or fix. thank you.
what i did first:
x=[-3:0.01:3];
f = sin(x)-x.*cos(x);
plot(x,f);
what i did next:
x=0;
Tol = 0.0000001;
count = 0;
dx=0;
f=sin(0)-0*cos(0);
fprintf('step x dx f(x)\n')
fprintf('---- ----------- --------- ----------\n')
fprintf('%3i %12.8f %12.8f %12.8f\n',count,x,dx,f)
while (dx > Tol)
count = count + 1;
fprime = x.*sin(x);
xnew = x - (f./fprime);
dx=abs(x-xnew);
x = xnew;
f = sin(x)-x.*cos(x);
fprintf('%3i %12.8f %12.8f %12.8f\n',count,x,dx,f)
end
on the other homework problems, i received several answers, yet on this problem i received only one. did i make a mistake?

Accepted Answer

John D'Errico
John D'Errico on 10 Dec 2020
Edited: John D'Errico on 10 Dec 2020
Is there a good reason why you initialized dx to be zero?
Do you see that immediately after that, you start a while loop. What is the codition?
while (dx > Tol)
Now, ask yourself. What was dx again when the loop started?
What is the value of Tol?
Is this true? (dx > Tol)?
Do you expect the while loop to ever allow entrance into the code inside that loop? What would happen if you wrote this code fragment?
while false
disp('The sky is falling! (sincerely, Chicken Little)')
end
How many times would you expect to see anything written to the command window?
  4 Comments
N/A
N/A on 10 Dec 2020
This answer seems more right. Thank you for your recommendations. Please let me know if you have another.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!