Python循环问题,在某些迭代中变量没有被赋值

2024-05-15 16:19:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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()

Tags: importprincipalasnppltfloatsum赋值
2条回答

>>> (100.0 - 6.805590751165351) * (1.0029166666666666 - 1)

0.2718170269757688

>>> (100.0 - 6.805590751165351) * (1.0029166666666667 - 1)

0.2718170269757688

我想你需要更精确

我想如果你在下面输入以下语句

monthlyPrincipal.append(principal)

loanAmount -= principal

然后你就会得到你想要的结果。你知道吗

编辑:只是一个建议,为了得到更准确的每月付款,我从维基百科得到了一个公式来计算每月付款给定的初始贷款金额。你知道吗

这是一个使用这个公式的程序。你知道吗

import matplotlib.pyplot as plt 
# https://stackoverflow.com/questions/52845238/python-looping-issue-with-variable-not-being-assigned-to-on-certain-iteration
loanAmount = 500000.0
interestRate = 3.5
loanTerm = 30 # 30 years
loanTermMonths = loanTerm * 12 # 360 months

i = interestRate / 12 * .01
n = loanTermMonths

# get cash flows, (monthly payments), for Present Value of loanAmount
# https://en.wikipedia.org/wiki/Present_value
monthlyPayment = loanAmount * i / (1 - (1 + i)**(-n))

principal = loanAmount

monthlyInterest = []
monthlyPrincipal = []

for x in range(loanTermMonths):
    interest = principal * i
    monthlyInterest.append(interest)

    principalPortion = monthlyPayment - interest
    monthlyPrincipal.append(principalPortion)

    principal -= principalPortion

x1 = list(range(1, loanTermMonths+1))
y1 = monthlyInterest
x2 = list(range(1, loanTermMonths+1))
y2 = monthlyPrincipal

plt.plot(x1, y1, label = "Interest") 
plt.plot(x2, y2, label = "Principal")
plt.title('Loan Amortization')
plt.grid(True)
plt.xlabel('months') 
plt.ylabel('$') 
plt.show()

除了如何计算每月付款外,它和你的大致相同。你知道吗

相关问题 更多 >