每月最低固定固定付款代码不起作用-无限循环?

时间:2018-12-03 19:50:36

标签: r while-loop infinite-loop

我正在上Phyton的课程,但是我发现自己更多地使用R方式,并且尝试解决计算给定金额的最小固定每月付款的问题。我有以下代码尝试在R中运行:

balance = 4000
initBalance = balance
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate/12
month = 0
minPay = 10

calc <- function(month, balance, minPay, monthlyInterestRate) {
  while (month < 12) {
    unpaidBalance = balance - minPay
    balance = unpaidBalance + (monthlyInterestRate * unpaidBalance)
    month = month + 1
    print(balance)
  }
}

while(balance > 0) {
  balance = initBalance
  minPay = minPay + 10
  month = 0
  calc(month = month, balance = balance, minPay = minPay, monthlyInterestRate = 0.2/12)
  print(minPay)
}

但是当我运行它时,它会陷入无限循环。我想念什么?感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

尝试一下:

balance = 4000
initBalance = balance
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate/12
month = 0
minPay = 10

calc <- function(month, balance, minPay, monthlyInterestRate) {
  while (month < 12) {
    unpaidBalance = balance - minPay
    balance = unpaidBalance + (monthlyInterestRate * unpaidBalance)
    month = month + 1
    #print(balance)
  }
  return(balance)
}

balance = 4000
initBalance = 4000

while(balance > 0) {
  minPay = minPay + 10
  month = 0
  balance = calc(month = month, balance = initBalance, minPay = minPay, monthlyInterestRate = 0.2/12)
  print(minPay)
}

您可以使用显式公式(请参见https://en.wikipedia.org/wiki/Equated_monthly_installment):

P = 4000       # principal
r = 0.2 / 12   # rate p.m.
n = 12         # number of payments

A = P*( (r*(1+r)^n)/((1+r)^n-1))  
print(A)
#[1] 370.538