HI,

I have written a small program that uses a while loop to calculate how many years it takes for an investment to double given an interest rate:

However, I think there is something minor wrong with the calculation for years, since when testing I put in 100% it should say 1 year, yet says it takes 2 years.

def main():
    # Introduction
    print __doc__
        
    presVal = 1 # Set present value to $1
    intRate = input("Enter the Interest Rate >>") # Ask for the Interest Rate
    years = 0 # Start the years at zero
    futVal = presVal # Set the variable used to accumulate

    # Set the while loop
    while futVal <= presVal *2: # Continue 'while' futVal has not doubled
        futVal = futVal + futVal *((float(intRate)/100)) # Calc the next loop
        years = years + 1 # Add 1 to the years

    # Calculate the amount left of the part year
    fut = futVal%2
 
    # Print the answer   
    print            
    print "It takes approximately %0.2f years to double the present value" % (years-fut)

Any help would be most welcomed.

Edited 5 Years Ago by vegaseat: changed old PHP code tags

while futVal <= presVal *2

should be

while futVal < presVal *2

Right now, when the value is doubled, it still executes the loop once more.

With this change, you get an answer of "1.00 years."

Edited 5 Years Ago by vegaseat: oldcode tags

Simpler program:

you should type line by line so the indents come into it

#A program to determine how long it takes for an investment to double
def main():
    I=input("What is the annualized interest rate as a decimal?: ")
    i=0
    z=1
    while z<2:
        i=i+1
        z=(z*(1+I))
    if z>=2:
        print i
main()

Edited 5 Years Ago by Narue: Added code tags

This question has already been answered. Start a new discussion instead.