Problems with while expression in a script

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

Andreas Goser
Andreas Goser 2011년 3월 8일
I posted a suggestion to your first question. Can you test this and then re-consider / edit this one?

답변 (2개)

Walter Roberson
Walter Roberson 2011년 3월 8일

0 개 추천

Please see this FAQ
Matt Fig
Matt Fig 2011년 3월 8일

0 개 추천

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.

이 질문은 마감되었습니다.

제품

질문:

Leo
2011년 3월 8일

마감:

2021년 8월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by