Info
This question is closed. Reopen it to edit or answer.
Problems with while expression in a script
1 view (last 30 days)
Show older comments
disp('This program will calculate the number of years required for a savings account earning 5% annual interest to reach target value.')
I = input('Please enter the intial ammount put in the account: ');
T = input('Please enter the target ammount for the account: ');
Y=0;
%Expression:
while T ~= I*(1.05^Y)
Y = Y+1;
end
fprintf('It will take %i years to save up for your target ammount.',Y)
The one thing I have a problem with is that it only works for very small numbers such as it taking one year to go from 1 to 1.05 or 2 years from 1 to 1.1025. Also, I want to make it have a message telling the user to re enter values if the target value is less than the initial value.
1 Comment
Andreas Goser
on 8 Mar 2011
I posted a suggestion to your first question. Can you test this and then re-consider / edit this one?
Answers (2)
Matt Fig
on 8 Mar 2011
As Walter intimates, this is a floating point issue. Instead of using a tolerance, you might want to think about the problem at hand. For example:
while T - I*(1.05^Y)>0
Y = Y+1;
end
Of course you should also put a check in your code which insures (or errors when appropriate) that T>I initially.
0 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!