月利率固定且每年存款增加的存款总额是多少?

What is the total deposit with a fixed monthly interest rate and with more money adding to the deposit each year?

假设您有 50 美元,每月固定利率为 5%。第一年后,你以后每年加50美元,三年期末你得到的总金额是多少。

我在R中理解,可以简单计算为

((50 x 1.05^12) +50) x 1.05 ^12) + 50) x 1.05^12 = 540.64

有没有一种方法可以编写函数或循环,以便在计算大量年数(例如 10 年、15 年等)时无需手动输入?

你可以写一个简单的循环,这样容易理解:

get_calc_year_loop <- function(year) {
   ans <- 0
   for(i in seq_len(year)) {
     ans <- (ans + 50)*1.05^12
   }
   return(ans)
}

get_calc_year_loop(3)
#[1] 540.6386

但是,您也可以使用 Reduce 不循环执行此操作:

get_calc_year <- function(year) {
   Reduce(function(x, y) (x + 50) * 1.05^12, seq_len(year), init = 0)
}
get_calc_year(3)
#[1] 540.6386

我们可以通过 purrr

中的 reduce 来做到这一点
library(purrr)
get_calc_year <- function(year) {
       reduce(seq_len(year), ~ (.x + 50) * 1.05 ^12, .init = 0)
 }
get_calc_year(3)
#[1] 540.6386