这是我的代码:
a = 5;
x0 = 0.5;
tol = 1e-15;
MAX_ITER = 1000;
x(1) = x0;
for n = 1:MAX_ITER
x(n+1) = x(n) - (1./2).*(x.^3).*(a-(1./(x.^3)));
if abs(x(n+1)-x(n)) < tol*abs(x(n+1))
break;
end
end
x'
我不知道该怎么办,因为我只是遇到错误。我选择的函数是(1/x^2)-a
,它仍然在分母中给出可能是错误的分区。
答案 0 :(得分:0)
这是一个工作脚本,基于您发布的摘录中显示的等式:
% Define the parameters...
a = 5;
x0 = 0.5;
iter = 1000;
tol = 1e-15;
% Create a vector for storing the iteration results...
x = NaN(iter,1);
x(1) = x0;
% Perform the computation...
for n = 2:iter
x_prev = x(n-1);
x_curr = 0.5 * (x_prev + (a / x_prev));
x(n) = x_curr;
if abs(x_curr-x_prev) < tol*abs(x_curr)
break;
end
end
% Clear the preallocated vector from unused slots...
x(isnan(x)) = [];
% Output the result...
x = [x repmat(sqrt(5),numel(x),1)]
最终输出是:
x =
0.5 2.23606797749979
5.25 2.23606797749979
3.10119047619048 2.23606797749979
2.35673727264418 2.23606797749979
2.23915722273719 2.23606797749979
2.23607010853285 2.23606797749979
2.23606797750081 2.23606797749979
2.23606797749979 2.23606797749979
2.23606797749979 2.23606797749979
问题在于,您混淆通过向量上的索引提取的标量值以及对向量本身执行的逐元素操作。您的解决方案是矢量化解决方案和迭代解决方案之间的一半。