房贷计算器python代码
时间: 2023-11-20 20:56:22 浏览: 128
以下是一个房贷计算器的Python代码,支持等额本息和等额本金两种还款方式的计算:
```python
import math
# 等额本息还款方式
def calc_average_capital_plus_interest(p, r, n):
r_month = r / 12 # 月利率
a = (1 + r_month) ** n
b = (1 + r_month) ** n - 1
monthly_payment = p * r_month * a / b # 月均还款额
total_payment = monthly_payment * n # 还款总额
total_interest = total_payment - p # 总利息
return monthly_payment, total_payment, total_interest
# 等额本金还款方式
def calc_average_capital(p, r, n):
r_month = r / 12 # 月利率
monthly_principal = p / n # 每月应还本金
total_interest = 0 # 总利息
total_payment = 0 # 还款总额
for i in range(n):
monthly_interest = (p - i * monthly_principal) * r_month # 每月应还利息
monthly_payment = monthly_principal + monthly_interest # 每月应还款额
total_payment += monthly_payment # 累计还款总额
total_interest += monthly_interest # 累计还款总利息
print('第{}个月,月供本金:{}元,月供利息:{}元,月供总额:{}元'.format(i + 1, round(monthly_principal, 2), round(monthly_interest, 2), round(monthly_payment, 2)))
return monthly_payment, total_payment, total_interest
# 测试
p = 1000000 # 贷款本金
r = 0.0588 # 年利率
n = 360 # 贷款期限(月)
print('等额本息还款方式:')
mp1, tp1, ti1 = calc_average_capital_plus_interest(p, r, n)
print('月均还款额:{}元,还款总额:{}元,总利息:{}元'.format(round(mp1, 2), round(tp1, 2), round(ti1, 2)))
print('等额本金还款方式:')
mp2, tp2, ti2 = calc_average_capital(p, r, n)
print('月均还款额:{}元,还款总额:{}元,总利息:{}元'.format(round(mp2, 2), round(tp2, 2), round(ti2, 2)))
```
阅读全文