0

I have written the following algorithm in order to evaluate a function in MatLab using Newton's method (we set r = -7 in my solution):

function newton(r);
syms x;
y = exp(x) - 1.5 - atan(x);
yprime = diff(y,x);
f = matlabFunction(y);
fprime = matlabFunction(yprime);
x = r;
xvals = x
for i=1:8 
    u = x;
    x = u - f(r)/fprime(r);
    xvals = x
end

The algorithm works in that it runs without any errors, but the numbers keep decreasing at every iteration, even though, according to my textbook, the expression should converge to roughly -14 for x. My algorithm is correct the first two iterations, but then it goes beyond -14 and finally ends up at roughøy -36.4 after all iterations have completed.

If anyone can give me some help as to why the algorithm does not work properly, I would greatly appreciate it!

Kristian
  • 1,179
  • 12
  • 29
  • 43

2 Answers2

3

I think

x = u - f(r)/fprime(r);

should be

x = u - f(u)/fprime(u);

If you always use r, you're always decrementing x by the same value.

Daniel Fischer
  • 174,737
  • 16
  • 293
  • 422
  • Awesome! Now it works like a charm, and, of course, I see now that your answer is how the formula should be written :). Thanks a lot! – Kristian Jun 21 '12 at 22:51
1
syms x
y = exp(x) - 1.5 - atan(x); % your function is converted in for loop
x=-1;
n=10;
v=0;
for i=2:n
    x(i)=tan(exp(x(i-1))-1.5);
    v=[v ;x(i)]; % you will get solution vector  for each i value
end
v
Jonas G. Drange
  • 8,500
  • 2
  • 25
  • 36