我试图用while循环解决一些方程式。我有一个已知的固定输出。工作流程如下:
P = 100; %Desired output
x = 1; %Initial guess
while abs(something) > 1e-6
x1 = (25 * x)/2
x2 = 10x - x1
x3 = 20x - (x - x1 - x2)*2
x4 = (x - x1 - x2 -x3)*12
x5 = (x - x1 - x2 -x3) * 10 + x4
P1 = 2005x3
P2 = 1500x5
Pnew = P1 + P2
end
我希望计算x1
,x2
,...,x5
并在达到条件P = Pnew
时停止循环。由于我对MATLAB的适度了解,我们将不胜感激。
提前谢谢了。
附录:也许我没有解释清楚。我的目标是在达到条件P = Pnew
时停止循环。我的已知值P
和初始值x
。应该通过给定的一系列方程生成Pnew。满足条件时x
,x1
,x2
,...,x5
将拥有其值。因此x
不仅是计算其他未知数的初始值(x1
,x2
,...,x5
)。我尝试修改它但NaN
Pnew
,P1
,error
和inf
P2
,x
,...
P = 100; %Desired output
x = 1; %Initial guess
Pnew = P + 1
while abs(P - Pnew) > 1e-6
x1 = (25 * x)/2;
x2 = 10*x - x1;
x3 = 20*x - (x - x1 - x2)*2;
x4 = (x - x1 - x2 -x3)*12;
x5 = (x - x1 - x2 -x3) * 10 + x4
P1 = 2005 * x3;
P2 = 150 * x5;
Pnew = P1 - P2;
error = abs(P - Pnew);
x_new = x - .001 * error;
x = x_new;
end
答案 0 :(得分:1)
如果您不使用*
来增加代码,则代码会出错。我已为您修复了以下代码。您要找的something
是P - Pnew
。这是因为你试图找到差异并确保它超过1e-6以继续循环。
由于您需要Pnew
,因此您还应该对其进行初始计算。您应该注意,您的计算实际上并未使Pnew
收敛到P
。
P = 100; %Desired output
x = 1; %Initial guess
x1 = ( 25 * x ) / 2
x2 = 10 * x - x1
x3 = 20 * x - ( x - x1 - x2 ) * 2
x4 = ( x - x1 - x2 -x3 ) * 12
x5 = ( x - x1 - x2 -x3 ) * 10 + x4
P1 = 2005 * x3
P2 = 1500 * x5
Pnew = P1 + P2
while abs( P - Pnew ) > 1e-6
x1 = ( 25 * x ) / 2
x2 = 10 * x - x1
x3 = 20 * x - ( x - x1 - x2 ) * 2
x4 = ( x - x1 - x2 -x3 ) * 12
x5 = ( x - x1 - x2 -x3 ) * 10 + x4
P1 = 2005 * x3
P2 = 1500 * x5
Pnew = P1 + P2
end
您可能还应该;
终止该行以禁止计算输出。
这里的do-while循环可行,但Matlab没有。您可以使用封装来隐藏代码重复,也可以使用for
循环,如下所示。
P = 100; %Desired output
x = 1; %Initial guess
for i = 1:Inf
x1 = ( 25 * x ) / 2
x2 = 10 * x - x1
x3 = 20 * x - ( x - x1 - x2 ) * 2
x4 = ( x - x1 - x2 -x3 ) * 12
x5 = ( x - x1 - x2 -x3 ) * 10 + x4
P1 = 2005 * x3
P2 = 1500 * x5
Pnew = P1 + P2
if abs( P - Pnew ) < 1e-6
break;
end
end
如果您有无限循环,要设置预定义的迭代终止,您可以将i = 1:Inf
替换为i = 1:iterMax
,其中iterMax
是最大迭代次数。
答案 1 :(得分:1)
通常在数值计算中,不会测试相等性,因为计算机无法区分所有实数。您的情况实际上是令人满意的== P - Pnew
在代码中它看起来像这样
P = 100; % Desired output
x = 1; % Initial guess
Pnew = P + 1; % Something far off, just to get through the first check
MAX_ITERATION_COUNT = 10000; % a reasonable upper bound to your loop
loopCount = 0;
while abs(P - Pnew) > 1e-6 && loopCount < MAX_ITERATION_COUNT
loopCount = loopCount + 1;
x1 = (25 * x) / 2;
x2 = 10 * x - x1;
x3 = 20 * x - (x - x1 - x2) * 2;
x4 = (x - x1 - x2 - x3) * 12;
x5 = (x - x1 - x2 - x3) * 10 + x4;
P1 = 2005 * x3;
P2 = 1500 * x5;
Pnew = P1 + P2;
end
这应该适用于您的问题。
编辑:我添加了一个循环计数器,以防你的循环没有定期完成。