Bisection search [duplicate]
Asked Answered
S

2

-1

Possible Duplicate:
Using bisection search to determine

I have posted other thread but it did not receive answers thus i'm trying to provide some of my work to make more clear.

I need to use bisection method to determine monthly payment in order to pay off debt in one year exactly.

Here's some code:

originalBalance = 320000
annualInterestRate = 0.2
monthly_interest = annualInterestRate / 12
low = originalBalance/12
high = (originalBalance*(1 + monthly_interest)**12)/12
epsilon = 0.01
min_payment = (high + low)/2.0

while min_payment*12 - originalBalance >= epsilon:
    for month in range(0, 12):
        balance = (originalBalance - min_payment) * (1+monthly_interest)

    if balance < 0:
        low = min_payment
    elif balance > 0:
        high = min_payment
        min_payment = (high + low)/2.0
print "lowest payment: " + str(balance)

However, I receive very way off answer: 298222.173851

My friend told me that correct answer is : 29157.09

Which is a lot lower than my...I guess the problem is in rounding(which I did not do yet) and preserving the balance after every looping and resetting it if balance is over 0. I cannot figure out how to attempt this problem and please, help someone :)

Side answered 10/10, 2012 at 13:3 Comment(2)
this is PSET2 from edx 6.00x, isn't it?Cavorelievo
Made a function, started a while loop, iterated with a for loop through 12 months, checked whether a balance is negative or positive and adjusted a value of guess, repeated, done it. Three days and hurting eyes but I did it, people. Thanks. :)Side
A
4

This is the correct one.

originalBalance = 320000
annualInterestRate = 0.2
monthly_interest = annualInterestRate / 12
low = originalBalance/12
high = (originalBalance*(1 + monthly_interest)**12)/12
epsilon = 0.01
min_payment = (high + low)/2.0

while min_payment*12 - originalBalance >= epsilon:
    for month in range(0, 12):
        balance = (originalBalance - min_payment)/10 * (1+monthly_interest)

    if balance < 0:
        low = min_payment
    elif balance > 0:
        high = min_payment
        min_payment = (high + low)/2.0
print "lowest payment: " + str(balance)
Alvertaalves answered 13/10, 2012 at 22:27 Comment(1)
I looks like your line setting the new min_payment at the bottom is in the incorrect scope. It should not be in the elif but within the while loop.Fernandes
H
3

This is what you need

while abs(x) > epsilon:
    x = balance
    for month in range(0, 12):
        x = (x - ans) * (1+monthly_interest)
Hodess answered 11/10, 2012 at 15:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.