954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Python - Calculate no of years to double

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.

macca1111
Light Poster
36 posts since Oct 2006
Reputation Points: 10
Solved Threads: 0
 

[php]while futVal <= presVal *2[/php]

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."

LaMouche
Posting Whiz in Training
269 posts since Oct 2006
Reputation Points: 83
Solved Threads: 39
 

Thank you. Stupid mistake I guess...

macca1111
Light Poster
36 posts since Oct 2006
Reputation Points: 10
Solved Threads: 0
 

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()
NoddyNUIG
Newbie Poster
1 post since Apr 2011
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You