Newton and Secant method using MATLAB

932 Views Asked by At

For a homework question I am supposed to be using the Newton and secant methods to find the roots of the function $F (x) = 0.11 + x + 0.8x \sin(\pi x)$ for $n=0$ to $n=12$ with initial guesses $x_0=-1.1$ and $x_1=-0.9$ and displaying the results in vector variables x_newton and x_secant. So far I have the following code:

%Newton method

f = @(x) 0.11+x+0.8*x*sin(pi*x);
df = @(x) 1+0.8*sin(pi*x)+0.8*x*pi*cos(pi*x);
x(1)=-1.1;
tol=1e-14;
for n=1:12
    x(n+1)=x(n)-f(x(n))/df(x(n));
    if ( abs(x(n+1)-x(n)) <= tol*abs(x(n)) )
        break
    end
end
x_newton = x(:)
x4=x(5)

%secant method

x(2)=-0.9
tol=1e-14;
for n=2:13
    x(n+1)=x(n)-f(x(n))/(f(x(n))-f(x(n-1)));
    if ( abs(x(n+1)-x(n)) <= tol*abs(x(n)) )
        break
    end
end
x_secant = x(:)
x4=x(5)

However my results from the Newton method and the secant method are extremely different; would someone be able to point out where I'm going wrong?

1

There are 1 best solutions below

2
On

The secant method uses the approximation $$ f^{\prime}(x_{n})\approx\frac{f(x_{n})-f(x_{n-1})}{x_{n}-x_{n-1}}, $$ but your code uses the incorrect approximation $$ f(x_{n})-f(x_{n-1}). $$