Calculating Payment Size Using Bisection Method in Python

91 Views Asked by At

I've been working on this problem for MIT's edX course. The goal of the problem is to calculate the payment size for one year given the loan size and APY. My problem is that my answer keeps coming up too high. I'm not exactly sure why this is. Any help would be greatly appreciated.

Here is the code:

b = float(input("balance = "))
r = float(input("annualInterestRate = "))
t = float(input("How many months do you want to take = "))
p = (b / t)
bval = []
new = b


def interest(b, r, p, t):

    bal = (b - p)
    max = (b * (1 + r / 12)**(12))/12
    min = (b / t)

    def update(bal, r):
        balance = (bal + (r / 12.0) * bal)
        return balance

    if len(bval) < t:
        bval.append(update(bal, r))
        return(interest(bval[-1], r, p, t))

    if (len(bval) == t):
        if bval[-1]< 10:
            return print(" Minimum payment: %i" % p)

        p = (max + min) / 2.0

        if bval[-1] < 0:
            min = bval[-1]
        elif bval[-1] > 0:
            max = bval[-1]

        bval.clear()
        bval.append(update((new - p), r))
        return(interest(bval[-1], r, p, t))

interest(b, r, p, t)
1

There are 1 best solutions below

1
On

There may be an issue with your order of operations in max. You might want to try adding parentheses around 1+r before dividing it by 12.