HiveBrain v1.2.0
Get Started
← Back to all entries
debugpythonMinor

For a given balance and an annual interest rate, calculate the minimum fixed monthly payment to pay off debt in a year

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thepaymentyearbalancerateminimumdebtmonthlyfixedpay

Problem

Interest is compounded monthly. Payment doesn't vary from month to month.

Version 1

balance = 999999
annualInterestRate = 0.18
mRate = annualInterestRate/12
high = (((mRate+1)**12)*balance)/12
low = balance/12
guessed = False

def balanceLeft(balance,mRate,minPayment):
    monthsLeft = 12
    while monthsLeft > 0:
        unpaidBalance =  balance - minPayment
        interest = mRate * unpaidBalance
        balance = unpaidBalance
        balance += interest
        monthsLeft -= 1
    return balance

while guessed == False:
    minPayment = (high + low) / 2
    if round(balanceLeft(balance,mRate,minPayment),2)  0:
        low = minPayment
    else:
        if abs(round(balanceLeft(balance,mRate,minPayment),2) - 0) < 0.01:
            guessed = True

print('Lowest Payment: ',end='')
print(round(minPayment,2))


Version 2

annualInterestRate = 0.18
rate = annualInterestRate / 12
monthsLeftr = 12
xCoefficent = 1 + rate
ConstantTerm = 1 + rate
while monthsLeftr > 1:
    xCoefficent = (xCoefficent + 1) * ConstantTerm
    monthsLeftr -= 1

balance = 999999
monthsLeft = 12
while monthsLeft > 0:
    balance = balance * ConstantTerm
    monthsLeft -= 1
minPayment = balance / xCoefficent

print('Lowest Payment: ', end="")


I would like a comparative and overall review, please!

Solution

This is a problem that can be solved exactly with a little math, so there should be no need to program a search.

Suppose that we borrow initial capital \$c\$ at a monthly interest rate \$r\$, paying it off in \$n\$ months with a monthly payment \$p\$. (Here \$r\$ is expressed as a multiplier, for example if the monthly percentage rate is \$2\%\$ then \$r = 1.02\$.)

In this scenario the outstanding balance is $$ \eqalign{
cr - p &= cr^1 - p(1) & \quad\text{after 1 month;} \\
(cr - p)r - p &= cr^2 - p(1 + r) & \quad\text{after 2 months;} \\
((cr - p)r - p)r - p &= cr^3 - p(1 + r + r^2) & \quad\text{after 3 months;}}$$ and so after \$n\$ months the balance is $$
cr^n - p(1 + r + r^2 + \dots + r^{n - 1}) = cr^n - p{r^n - 1\over r-1}. $$ If this pays off the debt exactly then $$ cr^n - p{r^n - 1\over r-1} = 0 $$ and so $$ p = {cr^n(r-1) \over r^n - 1}.$$

Since payments typically have to be made in integer numbers of pennies (or whatever the minimum unit of account is) then you'll want to round \$p\$ up to the nearest penny.

Context

StackExchange Code Review Q#142676, answer score: 7

Revisions (0)

No revisions yet.