我是Python新手,我遇到了一些bug,在某个迭代中,在循环外声明的变量只有在特定的迭代之后才被赋值。你知道吗
第8次迭代的第28行(x==7)interest
计算错误(可能没有赋值或其他什么),并且在其余的迭代中保持相同的值。变量值似乎卡住了。你知道吗
import matplotlib.pyplot as plt
import numpy as np
loanAmount = 500000.0
interestRate = 3.5
loanTerm = 30.0
monthlyInterest = []
monthlyPrincipal = []
compoundingRate = float((((interestRate / 12) * 0.01) + 1))
loanTermMonths = float(loanTerm * 12)
preInterestMonthly = loanAmount / loanTermMonths
lastMonthWithInt = preInterestMonthly * compoundingRate
i = 1
sum = 0.0
while i < loanTermMonths - 1:
lastMonthWithInt = lastMonthWithInt * compoundingRate
sum += lastMonthWithInt
i += 1
baseMonthly = sum / loanTermMonths
interest = 0.0
principal = 0.0
x = 0
while x < loanTermMonths - 1:
interest = float((loanAmount - principal) * (compoundingRate - 1))
principal = baseMonthly - interest
monthlyInterest.append(interest)
monthlyPrincipal.append(principal)
x += 1
x1 = np.arange(1, loanTermMonths)
y1 = np.array(monthlyInterest)
x2 = np.arange(1, loanTermMonths)
y2 = np.array(monthlyPrincipal)
plt.plot(x1, y1, label = "Interest")
plt.plot(x2, y2, label = "Principal")
plt.xlabel('months')
plt.ylabel('$')
plt.show()
>>> (100.0 - 6.805590751165351) * (1.0029166666666666 - 1)
0.2718170269757688
>>> (100.0 - 6.805590751165351) * (1.0029166666666667 - 1)
0.2718170269757688
我想你需要更精确
我想如果你在下面输入以下语句
monthlyPrincipal.append(principal)
loanAmount -= principal
然后你就会得到你想要的结果。你知道吗
编辑:只是一个建议,为了得到更准确的每月付款,我从维基百科得到了一个公式来计算每月付款给定的初始贷款金额。你知道吗
这是一个使用这个公式的程序。你知道吗
除了如何计算每月付款外,它和你的大致相同。你知道吗
相关问题 更多 >
编程相关推荐