使用 R 求解递归函数 [英] Using R to solve a recursion function

查看:53
本文介绍了使用 R 求解递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 R 的新手,我尝试解决递归函数:给定

I am new to R, and I try to solve a recursion function: given

### creating variable R, a vector of length 10
R = c(-1.70, 0.61, -0.54, -2.40, -1.50, -1.07, -2.42, -1.62, -1.65, -1.58)  

然后有一个模型:R[t] = A(t) + 0.5*A(t-1) + 0.3*A(t-2),其中A(0) = A(-1) = 0,然后计算A(i),i=1,2...10.我写的代码如下,但它总是给我错误,我不确定我错在哪里.请帮助我,非常感谢.

Then there is a model: R[t] = A(t) + 0.5*A(t-1) + 0.3*A(t-2), where A(0) = A(-1) = 0, then calculate the A(i), i=1,2...10. I wrote the code as following, but it always give me error and I am not sure where I am wrong. plz help me, many thanks.

ma <- function(a){
                  r = NULL 
                  a = NULL
                  r[1]=1.70
                  r[2]=0.61
                  r[3]=-0.54
                  r[4]=-2.40
                  r[5]=-1.50
                  r[6]=-1.07
                  r[7]=-2.42
                  r[8]=-1.62
                  r[9]=-1.65
                  r[10]=-1.58
                  a[0] = 0
                  a[-1] = 0
                  for(i in 1:10){
                    r[i]=a[i]+0.5*a[i-1]+0.3*a[i-2]
                    return(a[i])
                  }
                 }

推荐答案

您仍然可以使用函数.只需按原样编写递归函数 A.

You can still use function. Just write the recursive function A as it is.

A <- function(n, r=c(1.70, 0.61, -0.54, -2.40, -1.50, -1.07, -2.42, -1.62, -1.65, -1.58)) {
  if (n<=0) {
    0
  } else {
    0.5 * A(n-1) + 0.3 * A(n-2) - r[n]
  }
}

> A(5)
[1] -0.2895

这篇关于使用 R 求解递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆