%求解目标函数:f(x) = cos(x) - x^3
%x0 is initial value
%err: stop condition
%output root: the root of the function
function root = NewtonMethod(x0,err)
f_x0 = cos(x0) - x0^3;%f(x0)的函数值
f_x0_diff = -sin(x0)-3*x0^2;%f(x0)的导数
x1 = x0 - f_x0/f_x0_diff;
delta = abs(x1 - x0);
while delta > err
x0 = x1;
f_x0 = cos(x0) - x0^3;
f_x0_diff = -sin(x0)-3*x0^2;
x1 = x0 - f_x0/f_x0_diff;
delta = abs(x1 - x0);
end
root = x1;