簡體   English   中英

R中的牛頓法計算利率

[英]Calculating interest rate Newton's method in R

我們必須計算以下內容,而我完全一無所知。

一位消費者要求獲得 200000 歐元的信用額度來購買新房。 銀行建議采用以下還款計划:每月支付 2000 歐元(貸款后一個月開始),為期 30 年。 使用牛頓根來確定消費者的月利率。 將容差水平設置為 ε = 0.000001。

這是我的算法,它基本上可以工作,但我在實現它時遇到了問題。

  x0 <- 0
  n <- 0
while (n <= n_max) {
  n <- n + 1
  y0 <- f(x0)
  y1 <- f_prime(x0)
  if (y1 < eps) {
    break(0)
  }
  x1 <- x0 - (y0/y1)
  if (abs((x0 - x1) / x1) < eps) {
    print('convergent')
    break(0)
  }
  x0 <- x1
  print(paste(label = 'iterations', n, label = 'approximate root', x0))
  }
}
newton_root()

算法是對的,代碼不對。 在這里,更正了。
最后有一個uniroot解決方案,驗證代碼的解決方案。

newton_root <- function(f, f_prime, x_initial = 0, n_max = 50, eps, params){ 
  x0 <- x_initial
  n <- 0
  while (n <= n_max) {
    n <- n + 1
    y0 <- f(x0, params)
    y1 <- f_prime(x0, params)
    if (y1 < eps) {
      break
    }
    x1 <- x0 - (y0/y1)
    if (abs((x0 - x1) / x1) < eps) {
      message('convergent')
      break
    }
    x0 <- x1
    msg <- sprintf("iterations: %d, approximate root: %f", n, x0)
    message(msg)
  }
  x0
}
f <- function(r, params){
  K <- params[1]
  m <- params[2]
  Tot <- params[3]
  K*(1 + r)^m - Tot
}
f_prime <- function(r, params){
  K <- params[1]
  m <- params[2]
  K*m*(1 + r)^(m - 1)
}

pars <- c(200000, 30, 2000*12*30)
tol <- 1e-6
newton_root(f, f_prime, eps = tol, params = pars)
#iterations: 1, approximate root: 0.086667
#iterations: 2, approximate root: 0.061219
#iterations: 3, approximate root: 0.047266
#iterations: 4, approximate root: 0.043800
#iterations: 5, approximate root: 0.043623
#iterations: 6, approximate root: 0.043622
#convergent
#[1] 0.04362246

uniroot(f, c(0, 1), pars, tol = tol)$root
#[1] 0.04362262

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM