Mengezi Dhlomo
Mengezi Dhlomo

Reputation: 335

Working out number of years in compound interest using python function

School Question:

Build a function retirement_age(PMT, i, FV, start_age) that calculates the (whole) age at which your customer can retire, if they:

I am struggling to solve the number of years PMT would take to reach FV

This is my code:

def retirement_age(PMT, i, FV, start_age):
count = 0

while PMT <= FV: #PMT set to loop till it reaches FV
    PMT = PMT * (1+i)
    count = count + 1 #adds 1 to count value until while loop satisfied
    age = count + start_age #adds count value to start_age to determine retirement age
return int(age) #returns age

print (retirement_age(20000, 0.1, 635339.63, 20))

my answer with this code:

57

The answer is supposed to be:

35

I can't tell what I'm doing wrong. And the task specifically mentions that we are not allowed to import external functions like math for example, which means I can't use math.log() which would probably solve all my problems.

Upvotes: 0

Views: 1508

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45750

First, I'll note that broad debugging questions like this aren't very appropriate for SO.

Having said that, I played around with it and after reading the specs again, I found the issue(s). I figured I might as well post it.

  • You only need to keep calculating while the principal is less than the future value. You can stop once they're equal.

  • The main issues however were that you aren't adding any money each year. You're just accumulating interest on the initial principal. And...

  • You invested PMT immediately. The investment doesn't happen until the end of the year, as the instructions emphasize. That means at the start of the looping, he has 0 invested. That means he doesn't start accumulating interest until the start of the second loop/year.


def retirement_age(PMT, i, FV, start_age):
    age = start_age
    p = 0

    while p < FV:
        p = PMT + p * (1+i)
        age += 1

    return int(age)

print(retirement_age(20000, 0.1, 635339.63, 20))
# 35

I introduced p to keep track of the running balance since it's separate from what's being added each year. Your logic for keeping track of age was also a little convoluted, so I simplified it down a bit.

Upvotes: 1

Related Questions