【发布时间】:2019-01-23 17:03:12
【问题描述】:
我在 for 循环中有一个割线方法,试图将其更改为 while 循环,但问题只是显示了一次迭代,我想让它像 for 循环但在 while 循环中。
For循环的代码:
clc;clear;
x0=1;
x1=0;
f=@(x) 3*x+sin(x)-exp(x)
if abs(x0) <abs(x1)
t=x0;
x0=x1;
x1=t;
end
for i=1:5
x2=x1-(f(x1)*((x0-x1)/(f(x0)-f(x1))))
disp([x0, x1, x2, f(x2)]);
x0=x1;
x1=x2;
end
这是我的 while 循环代码:
clc; clear;
x0=1;
x1=0;
error=1
tol=0.00001;
f=@(x) 3*x+sin(x)-exp(x)
if abs(f(x0)) < abs(f(x1))
t=x0;
x0=x1;
x1=t;
end
x2=x1-(f(x1)*((x0-x1)/(f(x0)-f(x1))))
while(abs(f(x2))<tol)
disp(x1);
x0=x1;
x1=x2;
end
【问题讨论】:
标签: for-loop while-loop