Timdr
Timdr

Reputation: 21

Python function for calculating compound interest percentage

I'm new to programming, so any experienced programmer will probably be able to answer this question easily.

I am trying to write a Python function which will tell me what percentage compound interest is necessary to end up with a specific sum. For example, if I deposited $100, and after 17 years of compound interest I have $155, the function will tell me what percentage interest was I receiving. I wrote the following function, with 'start' being the original sum deposited, 'finish' the sum I ended up with, and 'years' the number of years it accrued interest. I designed it to give a result in decimal points, for example for 1.5% it will show 0.015.

Here's the code I wrote:

def calculate(start, finish, years):
    num = start
    percentage = 0
    while num < finish:
        percentage += 0.000001
        for year in range(years):
            num += num * percentage
    return percentage

print(calculate(12000, 55000, 100))

It's giving an output of 0.00017499999999999962 (i.e. 0.017499999999999962%), which is totally wrong.

I can't understand where I've gone wrong.

Upvotes: 2

Views: 1342

Answers (2)

Jessica
Jessica

Reputation: 51

You need to reset the num=start after every time you guess a percentage.

def calculate(start, finish, years):
    num = start
    percentage = 0
    while num < finish:
        num = start
        percentage += 0.000001
        for year in range(years):
            num += num * percentage
    return percentage
    
print(calculate(12000, 55000, 100))

However, you'd probably be better off solving this problem by simply re-arranging the compound interest formula:

A=P*(1+r/n)^(nt) 

(where A = Final balance, P = Initial balance, r = Interest rate, n = number of times interest applied per time period, and t = number of time periods elapsed.)

The rearrangement gives:

r=n((A/P)^(1/nt)-1)

and putting this into python gives us:

def calculate(start, finish, years):
    num = ((finish / start)**(1/years))-1
    return num

print(calculate(12000.0, 55000.0, 100.0))

which gives the expected results.

Upvotes: 4

Sura-da
Sura-da

Reputation: 331

You can do a one-liner if you understand how compound interest works

def calculate(start, finish, years):
    return (finish/start)**(1/years) - 1

print(calculate(12000, 55000, 100) * 100, '%')

Upvotes: 1

Related Questions