我有一个项目,我正在上学,我很确定我已经把它弄错了,但我不知道如何检查输出。我只是想知道我是否正确地做到了这一点。分配是让它显示每月付款和总利息。 这是我的代码
principal = float(input("Input Loan Principal: "))
# Principal amount borrowed input by user
loan_term = float(input("Input Loan Term In Years: "))
# Loan Term in years input by user
loan_interest = float(input("Input Loan Interest Rate: "))
# Loan interest in percentage input by user
monthly_rate = loan_interest / 100
# Loan interest percentage to decimal
loan_term_months = loan_term * 12
# Loan term from years to months
balance = principal
# Separate variable for calculations
math1 = (1.0 + monthly_rate) ** loan_term
math2 = (monthly_rate/(math1 - 1.0))
# Calculations
monthly_payment = (monthly_rate + math2) * balance
# Final Calculation for monthly payment
interest = (monthly_payment * loan_term) - principal
# Final Calculation for interest paid
final_monthly_payment = str(round(monthly_payment, 2))
final_interest = str(round(interest, 2))
# Rounding to two decimal points
print("Monthly payment: ", final_monthly_payment)
print("Effective Interest Paid: ", final_interest)
# Final print
感谢您提前提供任何帮助
答案 0 :(得分:0)
这是使用scipy fsolve检查答案的一种奇特方式:
import numpy as np
from scipy.optimize import fsolve
fv = 0
pv = 200000
rate = 0.075 / 12
nper = 15 * 12
def f(pmt):
return fv + pv*(1 + rate)**nper + pmt*(1 + rate*0) / rate*((1 + rate)**nper - 1)
pmt_amt = fsolve(f, [100], xtol=0.000001)
print(pmt_amt)
打印result
返回:
[-1854.02472001]
上面的主要概念是让scipy解决公式中的变量pmt
...这是付款金额。解释是,需要支付1,854.02美元才能在15年内以7.5%的价格偿还20万美元的贷款。
要查看每笔付款的本金和利息多少,numpy可以再次帮助您np.ppmt
和np.ipmt
。例如:
import numpy as np
fv = 0
pv = 200000
rate = 0.075 / 12
nper = 15 * 12
for per in range(nper):
principal = -np.ppmt(rate, per, nper, pv)
interest = -np.ipmt(rate, per, nper, pv)
print(principal, interest, principal + interest)
返回:
600.27301367 1253.75170634 1854.02472001
604.024720005 1250.0 1854.02472001
607.799874505 1246.2248455 1854.02472001
611.598623721 1242.42609628 1854.02472001
615.421115119 1238.60360489 1854.02472001
619.267497089 1234.75722292 1854.02472001
623.137918946 1230.88680106 1854.02472001
627.032530939 1226.99218907 1854.02472001
630.951484257 1223.07323575 1854.02472001
...
1797.15714344 56.8675765608 1854.02472001
1808.38937559 45.6353444143 1854.02472001
1819.69180919 34.3329108169 1854.02472001
1831.064883 22.9598370094 1854.02472001