0
我想使用平分搜索來找出多少月付款應該是爲了支付用戶將輸入的12個月內的全部餘額。但是,我寫的這段代碼進入了無限循環,顯示出「低,高,montlyPayment無限次」。我不知道哪個代碼導致這個問題,因爲條件語句對我來說似乎是正確的。平分搜索導致無限循環
initialBalance = float(raw_input('Enter the outstanding balance on your credit card'))
annualInterestrate = float(raw_input('Enter the annual credit card interest rate as a decimal'))
monthlyInterestrate = round(annualInterestrate, 2)
balance = initialBalance
while balance > 0:
numMonth = 0
balance = initialBalance
low = balance/12.0
high = (balance*(1+(annualInterestrate/12.0))**12.0)/12.0
epsilon = 0.01
monthlyPayment = round((high + low)/2.0, 2)
while abs(monthlyPayment*12.0 - initialBalance) >= epsilon:
print 'low =', low, 'high =', high, 'monthlyPayment =', round(monthlyPayment,2)
if monthlyPayment*12.0 < balance:
low = monthlyPayment
else:
high = monthlyPayment
monthlyPayment = round((high + low)/2.0, 2)
while balance > 0 and numMonth < 12:
numMonth += 1
interest = monthlyInterestrate * balance
balance -= monthlyPayment
balance += interest
balance = round(balance, 2)
print 'RESULT'
print 'monthly payment to pay off debt in 1 year:', monthlyPayment
print 'Number of months needed:', numMonth
print 'Balance:',balance
下聯:'餘額= initialBalance'。是設計還是偶然? –
我想知道通過反覆試驗找出一個近似結果的重點是什麼,同時你可以逆轉公式並立即得到確切的結果? – spectras
餘額= initialBalance是多餘的,但我不認爲這是造成這個問題的原因。這是我正在研究麻省理工學院開放課件的一個問題集,它指定了對分搜索的使用。 –