Potentially false result of derivatives in MatLab

35 Views Asked by At
clear; clc; close all;

f = @(x) sin(x) + cos(x);
df = @(x) (f(x+0.0001)-f(x))/0.0001;

tol = 1e-6;
iter = 0;
x_0 = 1;
while iter < 1000
    x_1 = x_0 - f(x_0)/df(x_0);
    if abs(f(x_1)) < tol
        break
    end
    x_0 = x_1;
    iter = iter + 1;
end
disp([x_1, f(x_1), iter])

The code block above shows calculates the root of an equation using the Newton-Raphson method. However, it reaches the result in only the 2nd iteration and the derivative equation given by my instructor which is supposed to give the derivative gives a different result than I expected. How can I ensure that the derivative is correct and the while loop gives the correct result in the end?

I tried to put the derivative manually but it gives a different result.

0

There are 0 best solutions below