2016-05-09 72 views
-1

下面的代码:MATLAB不会计算条件

clear; 
channel = ddeinit('view','tagname'); 
temperature = ddereq(channel,'temperature'); 
poistka = 0; 
time = 0; 
kvas = 0; 
ohrev= 1; 

steam=300; 
pressure=100; 
steam2= 50; 
tempom = 1; 
pom = 0; 
while time<3600 
ventil = ddereq(channel,'ventil');  
pause(0.1); 
time= time+1; 
pom = pom+1; 

if (kvas<=100) 
kvas = kvas+1; 
end; 

if (kvas>=100 && temperature<95 && ohrev==1) 

    temperature = temperature+1; 
    tempom=0; 

end; 

if (temperature==95) 
    ohrev=0; 

end; 

if (ohrev==0) 
temperature = temperature -0.1; 
tempom = 1; 

end; 

if (temperature==70) 
ohrev=1; 

end; 

    end; 

我与MATLAB comunnicating和InTouch中做的可视化,但我想不出为什么变量ohrev不会成为1temperature达到70的值。 它上升到95,然后下降到0但它应该停止在70并再次去95等,但它不起作用。任何建议?非常感谢您

+0

您的代码不完整 - 变量温度未启动。 – 16per9

+1

我的猜测:[不要执行与浮点数的精确匹配](http://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab ),特别是当他们计算未分配。 – TroyHaskin

+0

我运行你的代码,当kvas变为100时,变量温度上升到70并达到它的值。 – 16per9

回答

1

的问题是,你检查的70度的特定温度:

if (temperature==70) 
    ohrev=1; 
end; 

失败原因与有关浮点数的表示根本问题的事情。例如:

>> fprintf('%0.17e', 0.1) 
1.00000000000000010e-01 

注意,在MATLAB(和最通用的语言)的浮点字面0.1是不完全为MATLAB浮点数来表示。小数点后16位有一点额外的值。出于这个原因,一旦你开始从你的整数温度值减去0.1

if (ohrev==0) 
    temperature = temperature -0.1; 
    tempom = 1; 
end; 

你将不再有一个数字,恰好是一个整数值。因此,测试temperature == 70永远不会是真的。

一般的解决方案是总是使用容差检查浮点数。因此,而不是检查平等,做到以下几点:

tolerance = 1e-6; %% 0.000001; use whatever makes sense for your program 
if abs(temperature - 70) < tolerance 
    ohrev = 1; 
end 

这是一个普遍的问题浮点数工作的时候,所以我强烈recommmend阅读更多的,如果你要编写科学计划在MATLAB的话题(或Python或Java等)

更多:资源:

http://www.mathworks.com/matlabcentral/answers/57444-faq-why-is-0-3-0-2-0-1-not-equal-to-zero

Why can't decimal numbers be represented exactly in binary?

+0

是不是你的第二个名字?非常感谢你! 好吧,你知道,这是我的任务,我没有选择matlab ... – s0re

+0

:)好吧,就像我刚才提到的那样,使用本地工具几乎可以在任何语言中使用这个问题,但它很容易解决。有些软件包允许进行精确的算术运算,但它们通常比使用内置浮点功能慢得多。 – gariepy