我的代码:
monthlyInterestRate = annualInterestRate/12.0
low = balance/12
high = (balance*(1+monthlyInterestRate)**12)/12
guess = (low+high)/2
unpaidBalance = balance
month = 1
while True:
unpaidBalance= unpaidBalance-guess
while month < 13:
if unpaidBalance <= -0.1:
low = guess
month += 1
elif unpaidBalance >= 0.1:
high = guess
month += 1
else:
break
guess = (low + high)/2
print "Lowest Payment: " + str(round(guess, 2))
当我测试时,它会卡在“月份&lt; 13:”
的行上为什么要这样做以及如何解决?
答案 0 :(得分:1)
如果你在内心的每个循环中突破,你仍然不到13岁。
这一直在继续,因为您继续While True
并且不更新guess
。
我担心你在那里面临无限循环。
您的break
语句会破坏最近的循环,即While month < 13
循环。下一行未读。 guess
未更新。 while True
没有被打破。
也许你想说
while month < 13:
unpaidBalance= unpaidBalance-guess
if unpaidBalance <= -0.1:
low = guess
elif unpaidBalance >= 0.1:
high = guess
month += 1
guess = (low + high)/2
答案 1 :(得分:1)
你在这里
不是最好的解决方案,但它有效
monthlyPaymentRate = (balance*annualInterestRate/12)/((1-(1+annualInterestRate/12)**-12))
interest = monthlyPaymentRate * (annualInterestRate/12)
#print (monthlyPaymentRate)
#print (interest)
monthlyPaymentRate = (monthlyPaymentRate - interest) +1
#print (monthlyPaymentRate)
balanceInit = balance
epsilon = 0.01
low = monthlyPaymentRate
while low*12 - balance > epsilon:
balances = balanceInit
for i in range(12):
minpay = monthlyPaymentRate
unpaybal = balances - minpay
interest = (annualInterestRate /12) * unpaybal
smontfinal = unpaybal + interest
balances = smontfinal
#print('Remaining balance: ' ,round(balances,2) )
if balances <0:
low = -1
break
if balances < 0 :
low = -1
else:
monthlyPaymentRate =monthlyPaymentRate + 0.001
print('Lowest Payment:' ,round(monthlyPaymentRate,2) )