-1

我的代码:

balance = 320000
annualInterestRate = 0.2

originalBalance = balance
month = 1
monthly_interest = annualInterestRate / 12
low = originalBalance/12
high = (originalBalance*(1 + monthly_interest)**12)/12
epsilon = 0.01
min_payment = (high + low)/2.0

while min_payment*12 - originalBalance > epsilon:
    while month < 13:
        balance = (originalBalance - min_payment)/10 * (1+ monthly_interest)
        if balance <= 0.00:
            low = min_payment
            min_payment = (high + low)/2.0
        elif balance > 0.00:
            high = min_payment
            min_payment = (high + low)/2.0
        month += 1
print "Lowest payment: " + str(round(min_payment, 2))

但是,我得到 26666.0,而我实际上应该得到 29157.09。我究竟做错了什么?

4

3 回答 3

2

你忘记了重置month——它只有一次到13,然后内部循环再也不会运行了。

balance = 320000
annualInterestRate = 0.2

originalBalance = balance
month = 1
monthly_interest = annualInterestRate / 12
low = originalBalance/12
high = (originalBalance*(1 + monthly_interest)**12)/12
epsilon = 0.01
min_payment = (high + low)/2.0

while min_payment*12 - originalBalance > epsilon:
    month = 1          # < -- do this
    while month < 13:
        balance = (originalBalance - min_payment)/10 * (1+ monthly_interest)
        if balance < 0.00:
            low = min_payment
            min_payment = (high + low)/2.0
        elif balance > 0.00:
            high = min_payment
            min_payment = (high + low)/2.0
        month += 1
print "Lowest payment: " + str(round(min_payment, 2))
于 2013-02-25T22:20:07.557 回答
0

我想我看到的一个错误是你说high = (originalBalance*(1 + monthly_interest)**12)/12的。这样做是将high余额乘以一和利息之和。这可以。但是,您将这个数字取为 12 的幂,然后将其除以 12。在您的代码中,balance = 3000. 加上百分之二等于 3060。这个数字的 12 次方超过 6.74 e + 41,我不明白这个数字。这个除以 12 仍然是 5.61 e + 40。这个数字太长了,程序会崩溃(或者非常慢)。这必须在其他任何事情可能起作用之前进行更改。

于 2013-02-25T22:24:28.473 回答
0

我正在做同样的练习,这就是我注意到你的代码的地方:你写道:

if balance <= 0.00:
  low = min_payment
  min_payment = (high + low)/2.0

但是,我认为您应该将高值设置为等于 min_payment。如果余额小于零,那么您已经支付了太多费用,因此您的新二分搜索需要找到一个低于您上次 min_payment 猜测的数字。

于 2014-09-11T23:42:10.710 回答