I need to write a script for calculating the length of time it takes an input to double on 5% APR
here is what I have, I am just getting the incorrect answer. Is it a math or code issue? Any help appreciated.
i = float(input("What is your principal amount"))
r = float(.05)
year = 0
while i < (i * 2):
ie = (i * r)
i = i ie
year = 1
continue
else:
print("The number of years it takes for your sum to double is", year)
CodePudding user response:
The problem is that you tell the loop to stop when i
is greater than i*2
, however, every time the loop runs i*2
is recalculated. To fix this, you should make a variable to store the end number, then compare it to that. Like this:
i = float(input("What is your principal amount"))
r = float(.05)
year = 0
doubled = i * 2
while i < doubled:
ie = (i * r)
i = i ie
year = 1
continue
else:
print("The number of years it takes for your sum to double is", year)
If you use i < i*2
, then when i
is 1 the statement will be read as 1 < 2
. When i
is 2, the statement will be read as 2 < 4
. When i
is 3, the statement will be read as 2 < 6
. And so on... The loop will only end when the numbers get so large that Python just crashes.
On the other hand, if you use a variable, like doubled = i*2
, then i*2
will only be evaluated once.
However, in the real world you should always prefer math to loops. I understand that this is a homework assignment, but future visitors to this question should unconditionally use the formula instead. This is the code that uses the formula:
from math import log
apr = 0.05 # as a decimal
doublingTime = log(2) / log(1 apr)
print(doublingTime)