Can someone look over my newton's method script and see if it looks ok?

2 次查看(过去 30 天)
for F(X)=x^3-2x and F'(x)=3x^2-2 with initial guess of x=1
if true
% code
endx = 1;
Tol = 0.0000001;
count = 0;
dx=1;
f=-1;
fprintf('step x dx f(x)\n')
fprintf('---- ----------- --------- ----------\n')
fprintf('%3i %12.8f %12.8f %12.8f\n',count,x,dx,f)
xVec=x;fVec=f;
while (dx > Tol || abs(f)>Tol)
count = count + 1;
fprime = 3*x^2 - 2;
xnew = x - (f/fprime);
dx=abs(x-xnew);
x = xnew;
f = x^3 - 2*x;
fprintf('%3i %12.8f %12.8f %12.8f\n',count,x,dx,f)
end

采纳的回答

John D'Errico
John D'Errico 2014-11-19
编辑:John D'Errico 2014-11-19
Several obvious things.
First of all, you never evaluate f to start the method out. Yes, since you know the function f AND the starting value, f(1) = -1, so your code looks like it will work since you hard coded f initially as -1, but it is poor coding style anyway.
Second, I strongly suggest you learn not to hard code in your functions, like f(x) and f'(x). Learn to set up such a function up front, so you could use your code to solve a more general problem. For example, you could set up function handles up front...
f_x = @(x) x.^3 - 2*x;
fp_x = @(x) 3*x.^2 - 2;
I'd also suggest putting in a test for a MaxFunEvals or MaxIterations to prevent some problems. You also use the same Tol parameter for both a test on dx and on abs(f). While that might work on some problems, it is a bad idea in general.
  3 个评论
John D'Errico
John D'Errico 2014-11-19
编辑:John D'Errico 2014-11-20
It looks like you missed one other thing to make it work. You never defined an initial value for x. Ah, but as I write this, you have defined a variable endx, which I realize is a paste issue.
With that, I ran your code. The function you have has several roots. We can solve for them using roots, a numerical solver...
roots([1 0 -2 0])
ans =
0
1.4142
-1.4142
Or the symbolic way, as...
syms x
solve(x^3 - 2*x)
ans =
0
2^(1/2)
-2^(1/2)
In either case, the roots are 0 and +/-sqrt(2).
Running your Newton's method code, it yields a nice approximation to sqrt(2), one of the roots. As expected, it is quadratically convergent near the solution.
step x dx f(x)
---- ----------- --------- ----------
0 1.00000000 1.00000000 -1.00000000
1 2.00000000 1.00000000 4.00000000
2 1.60000000 0.40000000 0.89600000
3 1.44225352 0.15774648 0.11551761
4 1.41501064 0.02724288 0.00319099
5 1.41421424 0.00079640 0.00000269
6 1.41421356 0.00000067 0.00000000
7 1.41421356 0.00000000 0.00000000
So your code worked sucessfully as is.

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by