我必须创建一个代码来找到使用二分法在 12 个月内还清贷款所需的确切付款。我为此创建的代码有效,但它超出了它的目标。贷款将在 12 个月内还清,但在进行 12 次还款后,最终余额应为 0 左右。但这是一个更大的负数。
我正在使用的代码是:
StartBalance = float(raw_input('Credit Balance in $: '))
AnnualRate = float(raw_input('Annual interest rate in decimals: '))
MonthlyRate = AnnualRate / 12.0
MinPaymentLow = StartBalance / 12.0
MinPaymentHigh = (StartBalance*(1+MonthlyRate)**12.0)/12.0
cent = 0.01
Payment = (MinPaymentHigh+MinPaymentLow)/2.0
while (Payment*12-StartBalance) >= cent:
for month in range(0, 12):
Balance = (StartBalance-Payment)/10*(1+MonthlyRate)
if Balance < 0:
MinPaymentLow = Payment
elif Balance > 0:
MinPaymentHigh = Payment
Payment = (MinPaymentHigh + MinPaymentLow)/ 2.0
print 'RESULT'
print 'Number of months needed: 12'
print 'Montly pay: $', round(Balance,2)