# Loop answers slightly out from correct values

1 view (last 30 days)
Liam Crocker on 9 Sep 2020
Commented: John D'Errico on 10 Sep 2020
So in my script, I'm using a loop/ if else function. The values this function spits me out are very close to the Pi values in section 5 of my picture, however they arn't quite the same and I can't figure out Why. As the values get smaller and smaller the difference between the values I get and the answers on the table. However, my last formula of Pr/Rs*TI gives me answers that are correct according to the table in section 5. How is this possible when my Pi (called Pr) values are not correct?

Alan Stevens on 9 Sep 2020
Edited: Alan Stevens on 9 Sep 2020
Are the differences significant? We are unable to check all the numbers that went into the calculations given in the text. There is at least one difference between the table at the top of the text and the output table (T5 is given as 270.67 in the former and 270.65 in the latter, though this makes little practical difference). The largest relative error in Pr is only 0.03%
You don't need symbolic maths here, you can solve for Z directly in a single statement - see the listing below. I've tidied up some of the coding as well.
hi = [0 , 11 , 20, 32 , 47, 51 , 71 , 84.852 , 90 ];
Ti = [288.15, 216.65 , 216.65, 228.65 , 270.65, 270.65 , 214.65 , 186.946, 186.946];
ai = diff(Ti)./diff(hi);
go = 9.80666;
Rs = .287054;
B =(go/Rs);
Re = 6356.766;
Pi= 101325.0000;
Pr=Pi;
Hh=diff(hi);
Z = Re*hi./(Re - hi); % solve for Z directly
for i= 1:length(ai)
if ai(i) == 0
Pr(i+1) = Pr(i).*exp(-B*Hh(i)/Ti(i));
else
Pr(i+1) = Pr(i)*(Ti(i)/(Ti(i)+ai(i)*Hh(i))).^(B/ai(i));
end
end
fprintf('Z\n')
fprintf('%8.5f\n', Z)
fprintf('\n')
fprintf('Pr\n')
fprintf('%12.5f\n', Pr)
fprintf('\n')
fprintf('P_at_h\n')
P_at_h = Pr./(Rs.*Ti);
fprintf('%10.5f\n',P_at_h)
fprintf('\n')
% Text values
Prt = [101325.0000, 22632.0587, 5474.8862, 868.0180, 110.9062, 66.9388, 3.9564, 0.3734, 0.1457];
RelativeError = (Pr./Prt - 1)*100;
fprintf('Relative error (percent)\n')
fprintf('%5.4f\n',RelativeError)
Liam Crocker on 10 Sep 2020
I had a chat with my assssor and being out that far is negligent! Thank you for helping me and not just giving me the code or answer!
John D'Errico on 10 Sep 2020

Xavier on 9 Sep 2020
Unfortunately I can't debug the script as I don't have the Symbolic Maths Toolbox, however I would use
format long
when debugging to trace the error. An issue arises when using floating point numbers as due to the memory allocation process, random memory which is overwritten can be read again- there is more information on this here. This may account for the small differences in your numbers
Liam Crocker on 9 Sep 2020
Thank you!