我正在尝试为f(x)= e ^( - x)-sin(x)编码割线方法以找到最小的正根。我的代码似乎出错了。
%// Initial values and tolerance
x(0) = 2;
x(1) = 10;
f = @(x) exp(-x)-sin(x);
error = 0.001;
%// Different iterations
for k=0:100
x(k+1) = x(k) - (f(x(k)))*((x(k) - x(k-1))/(f(x(k)) - f(x(k-1))));
if abs(x(k)-x(k-1)) < error
return;
end
end
答案 0 :(得分:1)
为何出错?
正如您对问题的评论vector(1D matrix) indices in matlab run from 1
to end
中所述,在您的情况下,您尝试在代码中的不同位置访问无效索引:
%// Initial values and tolerance
x(0) = 2; %// <-- invalid index
x(1) = 10;
f = @(x) exp(-x)-sin(x);
error = 0.001;
%// Different iterations
for k=0:100
%// for k=0: x(k) and x(k-1) both invalid indices
%// for k=1: x(k-1) invalid index
x(k+1) = x(k) - (f(x(k)))*((x(k) - x(k-1))/(f(x(k)) - f(x(k-1))));
if abs(x(k)-x(k-1)) < error
return;
end
end
更正后的代码
我们更正了上述无效索引案例(将您的for
循环更改为while
循环):
%// Function to (attempt) to find a root to
f = @(x) exp(-x)-sin(x);
%// Initial values and tolerance
x(1) = 2;
x(2) = 10;
error = 0.001;
%// Different iterations
k=2;
maxIt = 100;
while (abs(x(k)-x(k-1)) > error) && (k-1 <= maxIt)
x(k+1) = x(k) - f(x(k))*(x(k) - x(k-1))/(f(x(k)) - f(x(k-1)));
k = k + 1;
end
%// print result
disp(['x(end) = ' num2str(x(end)) ...
', f(x(end)) = ' num2str(f(x(end))) ...
', iterations: ' num2str(k-2)]);
产生结果
x(end) = 6.285, f(x(end)) = -4.9315e-10, iterations: 7