Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my program calculating the compound interest twice

I want to calculate the time it takes for the compound interest to reach a certain goal by using Pn=(1+i)Pn−1.
What I have done is:

def my_saving_plan(P0,i,goal):
    P = [P0]
    years = 0
    for n in range(0,10000):
        if P[n] < goal: 
            P.append((1+i)*P[n-1])
            years += 1
            print(P)
        elif P[n] >= goal:
            return years
print(my_saving_plan(1000, 0.07, 2000))

But What I get from that is the number of compound interest twice. So for this example what I get is:

    [1000, 1070.0, 1070.0, 1144.9, 1144.9, 1225.0430000000001, 
1225.0430000000001, 1310.7960100000003, 1310.7960100000003, 
1402.5517307000005, 1402.5517307000005, 1500.7303518490005, 
1500.7303518490005, 1605.7814764784307, 1605.7814764784307,
 1718.186179831921, 1718.186179831921, 1838.4592124201556, 
1838.4592124201556, 1967.1513572895667, 1967.1513572895667, 
2104.8519522998363]
    21

Also I was wondering if there is a way to use a while loop instead of putting a ridiculous number in the for loop.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Might as well turn my comment into an answer:

def my_saving_plan(P0,i,goal):
    P = [P0]
    while P[-1] < goal:
        P.append((1+i)*P[-1])
        print(P)
    return len(P) - 1

print(my_saving_plan(1000, 0.07, 2000))

From my comment:
You have an off-by-one error in your append line. n is already the last element, and using n-1 will be one behind that, thus causing duplication.

You could also use while P[-1] < goal instead of for. Index -1 always refers to the last element. You don’t need n or years at all.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading