信用计算器产生错误输出

时间:2015-01-14 21:30:50

标签: python python-2.7 calculator currency

我需要计算所需的最低固定月付款,以便在12个月内偿还信用卡余额。正确的答案应该是310,但我得到340.我编辑代码几个小时,但没有找到任何合适的解决方案。这有什么不对?怎么可能修复它?

balance = 3329
annualInterestRate = 0.2
payment = 10

def year_balance(init_payment, init_balance):
    """ Calculates total debt after 12 months """
    interest_sum = 0
    for month in range(12):
        # balance after monthly payment
        unpaid = init_balance - init_payment 
        # monthly interest of remaining balance
        interest = unpaid * (annualInterestRate / 12.0) 
        interest_sum += interest
    yearly = init_balance + interest_sum # total debt after 12 months
    return yearly

total = year_balance(payment, balance) # total debt after 12 months

while total - payment * 12 > 0: 
# checks if payment is big enough to fully repay the credit after 12 months 
    payment += 10

print "Lowest payment: ", payment

2 个答案:

答案 0 :(得分:2)

您真的不需要迭代来计算每月还款。相反,您可以使用封闭形式的解决方案:

loan_amount = 3329
annual_interest_rate = 0.2
monthly_repayment = ((loan_amount * annual_interest_rate / 12.) /
                     (1 - (1 + annual_interest_rate / 12.) ** -12))
print monthly_repayment

这假定每月还款和每月复利。对于通用公式,请参阅,例如here

答案 1 :(得分:0)

我们需要为每个新的付款金额运行余额计数功能,因为对于更大的付款,利息金额会更小。所以

balance = 3329
annualInterestRate = 0.2
payment = 10


def year_balance(init_payment, init_balance):
    """ Calculates total debt after 12 months """
    interest_sum = 0
    unpaid = init_balance
    for month in range(12):
        # balance after monthly payment
        unpaid -= init_payment
        # monthly interest of remaining balance
        unpaid += unpaid * (annualInterestRate / 12.0)
    return unpaid

while year_balance(payment, balance) > 0:
    payment += 10

print("Lowest payment: ", payment)

注意:这是因为您在信用期开始前付款。如果您在一个月后完成此操作,则应首先添加每月利率。