r - 最低固定每月付款代码不起作用 - 无限循环?
问题描述
我正在学习 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)
}
但是当我运行它时,它会进入一个无限循环。我错过了什么?谢谢你的帮助。
解决方案
尝试这个:
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
推荐阅读
- bixby - 如何在 Bixby 上添加新的语音助手(其他国家/地区)
- scikit-learn - 如何在没有类型错误的情况下在 python 3.5.0 上导入 sklearn?
- javascript - 在控制台上打印环境变量但未定义
- reactjs - 无论是否使 setState 同步,都无法 setState
- c - 如何在 C 中继续程序之前等待字符串输入?
- javascript - 从文件输入设置背景图像后移动性能不佳
- cakephp - 更新后测试:找不到插件类`WyriHaximus\TwigView\Plugin`
- java - 什么是字符串值中的编码器?
- php - Laravel 419 错误 - 使用 Ajax 时出现 VerifyCsrfToken 问题
- python - 将列表中的相同元素写入txt文件