필터 지우기
필터 지우기

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