Home > database >  Calculating Compound Interest
Calculating Compound Interest

Time:11-01

I am trying to calculate compound interest but I could not be succesfull to write that. How can I fix the code?

Here is my code:

def compound_interest(money, lastmoney, rate):
    amountyear=(money*(1 rate//100))//lastmoney
    return amountyear

# store the inputs
money= float(input('money: '))
rate= float(input('Interest rate: '))
lastmoney= float(input('Last money: '))

amountyear= compound_interest(money, lastmoney, rate)
print(amountyear)

CodePudding user response:

The formula P(n 1) = (1 i)P(n) should give you a hint that either a loop or recursion is needed. Here's a recursive example:

def compound_interest(p0, i, goal):
  # Goal is reached - end recursion
  if p0 >= goal: return 0
  # Compute interest
  p0  = p0 * i
  # Call recursively. The  1 is adding one year to result
  return compound_interest(p0, i, goal)   1

print(compound_interest(1000, 0.05, 2000))
print(compound_interest(1000, 0.07, 2000))

Outputs:

15
11

CodePudding user response:

Using some math (solving for amountyears, see below), you can use the resulting formula to get your result.

import math


def compound_interest(money, lastmoney, rate):
    amountyear = math.log(lastmoney / money) / math.log(rate   1)
    return amountyear


# store the inputs
money = float(input('money: '))
rate = float(input('Interest rate: '))
lastmoney = float(input('Last money: '))

amountyear = compound_interest(money, lastmoney, rate)
print("exact: ", amountyear)  # 14.206699082890463
print("rounded to next year: ", math.ceil(amountyear))  # 15

Math:

Solving for n

CodePudding user response:

A non-recursive answer:

def n_years(P0, i, goal):
    n = 0
    running_total = P0
    while (running_total < goal):
        n  = 1                    # equivalent to n = n   1
        running_total *= (1   i)  # equivalent to running_total = running_total * (1   i)
    return n

n_years(1000, 0.07, 2000) # 11
n_years(1000, 0.05, 2000) # 15

Note that the variable running_total isn't necessary: I used it to make the code more legible.

CodePudding user response:

from math import log,ceil

def YearsToGoal(start,goal,interest):
    fExact = (log(goal)-log(start))/log(1 interest)
    return ceil(fExact)
  • Related