Loan payment calculation

元气小坏坏 提交于 2019-12-10 12:26:06

问题


I am learning Python and am stuck. I am trying to find the loan payment amount. I currently have:

def myMonthlyPayment(Principal, annual_r, n):
    years = n
    r = ( annual_r / 100 ) / 12
    MonthlyPayment = (Principal * (r * ( 1 + r ) ** years / (( 1 + r ) ** (years - 1))))
    return MonthlyPayment

n=(input('Please enter number of years of loan'))
annual_r=(input('Please enter the interest rate'))
Principal=(input('Please enter the amount of loan'))

However, when I run, I am off by small amount. If anyone can point to my error, it would be great. I am using Python 3.4.


回答1:


Payment calculation-wise, you don't appear to have translated the formula correctly. Besides that, since the built-in input() function returns strings, you'll need to convert whatever it returns to the proper type before passing the values on to the function which expects them to numeric values.

def myMonthlyPayment(Principal, annual_r, years):
    n = years * 12  # number of monthly payments
    r = (annual_r / 100) / 12  # decimal monthly interest rate from APR
    MonthlyPayment = (r * Principal * ((1+r) ** n)) / (((1+r) ** n) - 1)
    return MonthlyPayment

years = int(input('Please enter number of years of loan: '))
annual_r = float(input('Please enter the annual interest rate: '))
Principal = int(input('Please enter the amount of loan: '))

print('Monthly payment: {}'.format(myMonthlyPayment(Principal, annual_r, years)))



回答2:


I think in the last bit of your calculation,

/ (( 1 + r ) ** (years - 1))

you have your bracketing wrong; it should be

/ ((( 1 + r ) ** years) - 1)



回答3:


I think the correct formula is this,

MonthlyPayment = (Principal * r) / (1 - (1 + r) ** (12 * years))

I cleaned up your variables some,

def get_monthly_payment(principal, annual_rate, years):
    monthly_rate = annual_rate / 100 / 12
    monthly_payment = principal * (monthly_rate + monthly_rate / ((1 + monthly_rate) ** (12 * years) - 1))
    return monthly_payment

years = float((input('Please enter number of years of loan')))
annual_rate = float((input('Please enter the interest rate')))
principal = float((input('Please enter the amount of loan')))
print ("Monthly Payment: " + str(get_monthly_payment(principal, annual_rate, years)))

It would also be prudent to add a try-except block around the inputs.



来源:https://stackoverflow.com/questions/35387680/loan-payment-calculation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!