二分搜索最低支付(Python) - 答案太大了

时间:2016-01-24 15:37:15

标签: python

进行二分搜索以确定在1年内支付信用卡余额的最低月付款额。我的结果总是几百太大,无法在MITx:6.00.1x在线提交模块中打印(始终打印0.00)。有人可以提供一些建议吗?

代码:

balance = 999999
annualInterestRate = 0.18
interest = annualInterestRate / 12.0
lower = balance / 12.0
upper = (balance * (1+ interest)**12) / 12.0
guess = (upper + lower) / 2

remainder = balance
newBalance = 0

epsilon = 0.00000001

while (newBalance > epsilon):
    guess = (upper + lower) / 2
    for i in range (0,12):
        newBalance = remainder - guess
        remainder -= guess
        month_interest = newBalance * interest
        remainder = newBalance + month_interest

        if newBalance < 0:
            upper = guess
            newBalance = balance
        elif newBalance > epsilon:
            lower = guess
            newBalance = balance 
print "Lowest Payment: %.2f" %guess 

2 个答案:

答案 0 :(得分:1)

问题是,您设置了newBalance = 0。因此,while-condition newBalance > epsilon永远不会成立,你会直接进入print语句。将newBalance设置为1或其他。

答案 1 :(得分:1)

这里有很多问题。首先,如另一个答案中所述,while循环永远不会运行。如果确实如此,你将永远不会使用循环内的if \ elif模拟超过1个月的付款。而且,在开始新猜测时,您也永远不会重置remainder变量。

remainder -= guess在使用之前将其设置为其他两行时似乎毫无用处。

newBalance -= guess然后newBalance *= (1+interest)足以支付每月付款次数

balance = 999999
annualInterestRate = 0.18
interest = annualInterestRate / 12.0
lower = balance / 12.0
upper = (balance * (1+ interest)**12) / 12.0
guess = (upper + lower) / 2

newBalance = balance

epsilon = 0.00000001
while (newBalance > epsilon):
    guess = (upper + lower) / 2
    for i in range (12):
        newBalance -= guess
        newBalance *= (1+interest)

    if newBalance < 0:
        #print("Guess: {0}. {1}. Payed too much, start agian with new guess".format(guess, newBalance))
        upper = guess
        newBalance = balance
    elif abs(newBalance) > epsilon:
        #print("Guess: {0}. {1}. PAyed too little , start again with new guess".format(guess, newBalance))
        lower = guess
        newBalance = balance
print ("Lowest Payment: %.2f" %guess )


#Checking result
for i in range(12):
    balance -= guess
    balance *= (1+interest)
print(balance)

>>Lowest Payment: 90325.03
>>6.380723789334297e-09