0

我正在尝试使用二进制搜索(二分搜索?)解决在线问题,但我不确定我的代码哪里出错了,我的答案与预期的答案不同,对我来说有点不舒服。我真的很高兴知道我在哪里偏离了路线,以及对未来的指示。我得到一个年利率和一个初始余额。我还应该选择一个足够小的步长,这样我就可以递增到美分。我的代码是这样的:

startbalance = input('Balance: ')
annualInterestRate = input('annualInterestRate: ')
monthlyInterestRate = annualInterestRate / 12.0
balance = startbalance
step = 0.01
lowbound = balance / 12.0
highbound = (balance * (1 + monthlyInterestRate)**12) / 12.0
monthlyPayment = (lowbound + highbound) / 2.0

while (monthlyPayment - balance) >= step:

    for month in range(0, 12):
        balance -= monthlyPayment
        balance = balance + ((1 + monthlyInterestRate) * balance)

    if balance < 0:
        highbound = monthlyPayment
        balance = startbalance
    elif balance > 0:
        lowbound = monthlyPayment
        balance = startbalance

print 'Lowest Payment: ', round(monthlyPayment, 2)

使用案例中提供的值测试我的代码,我有以下内容:

With an annual interest rate of 0.2
and a balance of 320000,
My result: 29591.88 (incorrect, the answer should be 29157.09)

With an annual interest rate of 0.18
and a balance of 999999,
My result: 91484.0 (incorrect, the answer should be 90325.03)

我想我只是有点偏离,我真的很感激一些设置。

谢谢!

4

1 回答 1

0

修复它(谢谢,z0k!):

startbalance = input('Balance: ') annualInterestRate = input('annualInterestRate: ') monthlyInterestRate = annualInterestRate / 12.0 monthlyInterestRate = annualInterestRate / 12.0 startbalance = balance step = 0.01 lowbound = startbalance / 12.0 highbound = (startbalance * (1 + monthlyInterestRate)**12) / 12.0 monthlyPayment = (lowbound + highbound) / 2.0 while (abs(startbalance)) >= step: startbalance = balance for month in range(0, 12): startbalance -= monthlyPayment startbalance = startbalance + ((monthlyInterestRate) * startbalance) if startbalance < 0: highbound = monthlyPayment if startbalance > 0: lowbound = monthlyPayment monthlyPayment = (lowbound + highbound) / 2.0 print 'Lowest Payment: ', round(monthlyPayment, 2)

于 2016-01-29T21:44:43.087 回答