二等分搜索信用卡债务的最低支付:答案总是偏离

时间:2013-02-25 22:16:50

标签: python bisection

我的代码:

balance = 320000
annualInterestRate = 0.2

originalBalance = balance
month = 1
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:
    while month < 13:
        balance = (originalBalance - min_payment)/10 * (1+ monthly_interest)
        if balance <= 0.00:
            low = min_payment
            min_payment = (high + low)/2.0
        elif balance > 0.00:
            high = min_payment
            min_payment = (high + low)/2.0
        month += 1
print "Lowest payment: " + str(round(min_payment, 2))

然而,我得到26666.0,而我实际上应该得到29157.09。我做错了什么?

3 个答案:

答案 0 :(得分:2)

您忘了重置month - 它会转到13,然后内部循环再也不会运行。

balance = 320000
annualInterestRate = 0.2

originalBalance = balance
month = 1
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:
    month = 1          # < -- do this
    while month < 13:
        balance = (originalBalance - min_payment)/10 * (1+ monthly_interest)
        if balance < 0.00:
            low = min_payment
            min_payment = (high + low)/2.0
        elif balance > 0.00:
            high = min_payment
            min_payment = (high + low)/2.0
        month += 1
print "Lowest payment: " + str(round(min_payment, 2))

答案 1 :(得分:0)

我认为我看到的一个错误就是你说high = (originalBalance*(1 + monthly_interest)**12)/12。这样做是将high设置为余额乘以一和利息之和。这可以。但是,您正在使用该数字并将其置于12的幂,然后将其除以12.在您的代码中,balance = 3000。加上两个百分点等于3060.这个数字到12的幂超过6.74 e + 41,这个数字我不明白。除以12仍然是5.61 e + 40.这个数字是如此之长,程序将崩溃(或非常慢)。必须先改变它,然后才能发挥其他作用。

答案 2 :(得分:0)

我正在进行同样的练习,这是我注意到你的代码: 你写道:

if balance <= 0.00:
  low = min_payment
  min_payment = (high + low)/2.0

但是,我认为你应该设置高等于min_payment。如果余额小于零,那么你支付的金额太多了,所以你的新二分搜索需要找到一个低于你上一次min_payment猜测的数字。