Bisection搜索以查找导致无限循环的最小付款

时间:2017-11-13 23:07:01

标签: python bisection edx

这是我的第一篇文章,如果它不是最好的,请道歉!

我正在参加在线课程(Edx),并尝试编写二分法搜索,找到清算信用卡余额的最低金额。您将获得余额和年度信息率。我的代码遇到了无限循环,我无法弄清楚我做错了什么。

提供的测试条件 - 应产生最低付款:29157.09

balance = 320000
annualInterestRate = 0.2

monthlyInterestRate = annualInterestRate / 12.0
lower = balance / 12.0
upper = (balance * ((1 + monthlyInterestRate) ** 12.0)) / 12.0
guess = (upper + lower) / 2.0
valid = True
month = 0

def calculate(month, balance, guess, monthlyInterestRate):
    while month < 12:
        unpaidBalance = balance - guess
        balance = unpaidBalance + (monthlyInterestRate * unpaidBalance)
        month += 1
    return balance

while valid == True:
    if calculate(month, balance, guess, monthlyInterestRate) == 0:
        print('Min payment is: ', str(round(guess,2)))
        valid = False
    elif calculate(month, balance, guess, monthlyInterestRate) > 0:
        lower = guess
    elif calculate(month, balance, guess, monthlyInterestRate) < 0:
        upper = guess
    else:
        print('Invalid Input')
    guess = (upper + lower) / 2.0

关于我做错的任何想法?在此先感谢您的帮助!

0 个答案:

没有答案