Python - 查找信用卡的每月NPV

时间:2015-06-23 14:17:02

标签: python python-2.7

我正在运行这个程序:

balance = 320000
annualInterestRate = 0.2

monthlyPayment = 0.0
monthlyInterestRate = annualInterestRate/12
low = balance / 12.0
high = ((balance * ((1.0 + monthlyInterestRate)**12.0))/12.0)
monthlyPayment = (high+low)/2
while balance != 0:
    newBalance = balance
    for x in range(1, 13):
        lastMonthBalance = newBalance - monthlyPayment
        newBalance = lastMonthBalance + ((monthlyInterestRate) * lastMonthBalance)
        if -0.002 <= newBalance <= 0.002:
            balance = 0

    if newBalance < 0.0:
        low = 0
        high = monthlyPayment
    elif newBalance > 0.0:
        low = monthlyPayment

    monthlyPayment = (low + high) / 2

print "Lowest Payment: %.2f" % monthlyPayment

最初我试图找到使我的newBalance等于0的每月付款,但是由于处理时间的限制,我选择了不太准确的方法。

但是,当我将界限从-0.2 / 0.2更改为-0.002 / 0.002时,我的答案从14578.55更改为29157.09,我不明白为什么?

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

所以,我不完全确定原因,但通过删除low = 0的行,使代码工作。

工作代码是:

#Write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month.

balance = 999999
annualInterestRate = 0.18

monthlyPayment = 0.0
monthlyInterestRate = annualInterestRate/12
low = balance / 12.0
high = ((balance * ((1.0 + monthlyInterestRate)**12.0))/12.0)
monthlyPayment = (high+low)/2
while balance != 0:
    newBalance = balance
    for x in range(1, 13):
        lastMonthBalance = newBalance - monthlyPayment
        newBalance = lastMonthBalance + ((monthlyInterestRate) * lastMonthBalance)
        if -0.05 <= newBalance <= 0.05:
            balance = 0

    if newBalance < 0.0:
        high = monthlyPayment
    elif newBalance > 0.0:
        low = monthlyPayment

    monthlyPayment = (low + high) / 2

print "Lowest Payment: %.2f" % monthlyPayment

如果有人能向我解释为什么会这样,我会非常感激。