MATLAB: Issue with a while loop

bacsimplewhile loop

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

Best Answer

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...