"二分搜索导致无限循环"

2024-05-15 22:19:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用二等分搜索,找出每月应支付多少,以便支付12个月内用户将输入的全部余额。但是,我写的这段代码进入了无限循环,显示“低、高、月支付无限次”。我不知道是哪段代码导致了这个问题,因为条件语句对我来说是正确的。在

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

Tags: 代码inputrawfloatlowprintbalancehigh
1条回答
网友
1楼 · 发布于 2024-05-15 22:19:17

我把上面的问题重新编码为

balance = 120000
annualInterestRate = 0.1
rate=annualInterestRate/12.0
high=(balance * (1 + rate)**12) / 12.0
low=balance/12.0
payment=0
bal_ref=balance
unpaid=balance
N=0
while (abs(unpaid) > .01):
    month=0
    pay=(high+low)/2
    balance=bal_ref
    while(month < 12):
        unpaid=balance-pay
        balance=unpaid + (unpaid * rate)
        month +=1
    if (abs(unpaid) < .01):
        payment=pay
        break
    elif (unpaid > .01):
        low=pay
    elif (unpaid < -.01):
        high=pay
    N+=1
print("Payment:",round(pay,2))

相关问题 更多 >