issue with a while loop

2 次查看(过去 30 天)
Adam Palmer
Adam Palmer 2014-8-3
编辑: dpb 2014-8-4
Hey everybody, got a simple question for ya. Im making a function file to determine when it is safe to drive for a person who has been drinking. The value for hours in the output is wrong, but the formula works well outside of the loop. The answer should be around 2-3 hours, but the while loop consistently returns .28 hours. Heres my code
BAC=.13;
Hrs=0;
Rt=.0140;
while BAC>.08
BAC=BAC-(Hrs*.0140);
Hrs=Hrs+.01
end
  1 个评论
Azzi Abdelmalek
Azzi Abdelmalek 2014-8-3
If the formula works well outside the loop, then don't use the loop

请先登录,再进行评论。

采纳的回答

dpb
dpb 2014-8-3
编辑:dpb 2014-8-3
You've got the while operating until BAC<=0.08 by adjusting Hrs but one can take the expression
BAC=BAC-(Hrs*.0140);
and solve for
0.08=0.13-Hrs*0.014
to find
>> (0.13-0.08)/0.014
ans =
3.5714
>>
What's wrong with your implementation that iterates where it isn't really needed is you're multiplying the difference/0.01 hr by the total hours every time instead of just the reduction/0.01 hr.
>> BAC=.13;
Hrs=0;
dHr=0.01;
Rt=.0140;
dHrRed=dHr*Rt;
while BAC>.08
BAC=BAC-dHrRed;
Hrs=Hrs+.01;
end
Hrs
Hrs =
3.5800
>>
This isn't quite as accurate as the direct solution but given the inherent nature of the problem the correlation probably isn't accurate to a tenth of an hour, either...
  2 个评论
Adam Palmer
Adam Palmer 2014-8-3
Thanks dpb, Im still getting the hang of while loops as you can see lol
dpb
dpb 2014-8-3
编辑:dpb 2014-8-4
No problem; took me a few minutes to grok the issue, too.
OBTW, the above leaves Hrs at 0.01 greater than the actual solution because of the location of the increment of Hrs after the computation. The exit test doesn't occur until after that last increment but the final BAC value is based on the previous Hrs value.
To see this, try a modification...
BAC=.13;
Hrs=0;
dHr=0.01;
Rt=.0140;
dHrRed=dHr*Rt;
while BAC>.08
BAC=BAC-dHrRed;
if Hrs>=3.5, disp([Hrs BAC]), end
Hrs=Hrs+dHr;
end
3.5100 0.0807
3.5200 0.0806
3.5300 0.0804
3.5400 0.0803
3.5500 0.0802
3.5600 0.0800
3.5700 0.0799
>> disp([Hrs BAC])
3.5800 0.0799
>>
So, the answer is closer to the analytic for this particular set of values but your resolution is still only 0.01 hr, of course.
To fix this to get the nearest, rearrange it slightly --
BAC=0.13;
dHr=0.01;
Hrs=-dHr; % initialize to minus the delta
Rt=0.0140;
dHrRed=dHr*Rt;
while BAC>.08
Hrs=Hrs+dHr; % and increment first
BAC=BAC-dHrRed;
end

请先登录,再进行评论。

更多回答(1 个)

Star Strider
Star Strider 2014-8-3
For zero-th order elimination kinetics, the loop should actually be:
BAC=.13;
Hrs=0;
Rt=.0140;
while BAC>.08
BAC=BAC-(0.01*.0140);
Hrs=Hrs+.01
end
This gives Hrs = 3.58.

类别

Help CenterFile Exchange 中查找有关 Historical Contests 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by