[英]R: Recursive sum of functions of x
I would like to program a sum of k functions of x depending upon a index i=1,...k, and also depending on the a point x0 (it looks a bit like a Taylor formula). 我想根据索引i = 1,... k来编程x的k个函数的总和,并且还取决于点x0(它看起来有点像泰勒公式)。 However, the following code produces the error message:
但是,以下代码生成错误消息:
Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
错误:评估嵌套太深:无限递归/选项(表达式=)?
Error during wrapup: evaluation nested too deeply: infinite recursion / options(expressions=)?
换行时出错:评估嵌套太深:无限递归/选项(表达式=)?
I would appreciate if somebody could help to improve on it: 如果有人可以帮助改进它,我将不胜感激:
cum_f <- function(x, x0, k){
i <- 1
p <- function(x,x0) x0^2
while(i <= k){
p = function(x,x0){ p(x,x0) + (x - x0)**i }
i = i + 1
}
return(p(x,x0))
}
cum_f(x,1,5)
cum_f(10,1,5)
Do you need recursion? 你需要递归吗? Is this what you're looking to do?
这是你想要做的吗?
cum_f <- function(x, x0, k){
i <- 1
p <- x0**2
while(i <= k){
p <- p + (x - x0)**i
i = i + 1
}
return(p)
}
cum_f(10,1,5)
# 66430
You can get the same result with this function 您可以使用此功能获得相同的结果
cum_f <- function(x, x0, k){
val <- Reduce("+", c(x0**2, (x-x0)**(1:k)), accumulate=TRUE)
return(tail(val,1))
}
Or even simpler (thanks Roland) 甚至更简单(感谢罗兰)
cum_f <- function(x, x0, k){
val <- x0^2 + sum((x-x0)^(1:k))
return(val)
}
cum_f(10,1,5)
# 66430
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.