gpt4 book ai didi

python - 用 Python 比较贷款

转载 作者:太空宇宙 更新时间:2023-11-04 08:51:13 24 4
gpt4 key购买 nike

我正在为我的 Python 类(class)做作业。我几乎弄明白了,但我的输出与原始问题中显示的略有不同。当利率为 5.125% 时,我的月供为 189.29,但问题的输出为 188.28。没有格式的原始数字是189.286。我想也许在金融系统中,他们只是简单地削减小数而不是使用“舍入”。我不确定在 Python 中是否有任何方法可以做到这一点。问题就在这里。

编写一个程序,让用户输入贷款金额和贷款年限,并显示每个利率从 5% 到 8% 的每月还款额和总还款额,增量为 1/8。

输入:

Loan Amount: 10000
Number of Years: 5

输出:

Interest Rate   Monthly Payment Total Payment
5.000% 188.71 11322.74
5.125% 189.29 11357.13
...
7.875% 202.17 12129.97
8.000% 202.76 12165.84

代码:

LoanAmount = float(input("Loan Amount:"))
NumOfYears = float(input("Number of Years:"))
AnnualRate = float(5.0)
print("\nInterest Rate\t" + "Monthly Payment\t" + "Total Payment")
while (AnnualRate <= 8.0):
MonthlyRate = float(AnnualRate/1200)
MonthlyPayment = float(LoanAmount * MonthlyRate / (1- 1/ pow(1+MonthlyRate, NumOfYears *12)))
TotalPayment = format(MonthlyPayment * NumOfYears * 12, ".2f")
print (format(AnnualRate, ".3f"), end = "%\t\t")
print (format(MonthlyPayment, ".2f"), end = "\t\t")
print(TotalPayment, end = "\n")
AnnualRate += 1.0/8

最佳答案

当您处理金钱时,请使用 decimal模块。这允许许多不同的 rounding modes .例如,向下舍入:

import decimal

payment = decimal.Decimal('189.286')
with decimal.localcontext() as ctx:
ctx.rounding = decimal.ROUND_DOWN
print(round(payment, 2))

打印:

189.28

Bankers' rounding会是:

decimal.ROUND_HALF_EVEN

Round to nearest with ties going to nearest even integer.

with decimal.localcontext() as ctx:
ctx.rounding = decimal.ROUND_HALF_EVEN
print(round(payment, 2))

关于python - 用 Python 比较贷款,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35079545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com