Following is a recursive function which takes as input (argument) a vector $x$ and returns a scalar. Either by looking carefully at the function, or by running the function with a few simple input vectors and observing the returned values in each case, determine what the function is doing.
```{r}
myfun <- function(x) {
if (length(x) == 1) {
return(x)
} else
return(x[1] + myfun(x[-1]))
}
myfun(c(1:1000)) #here's what happens when it is applied to 1:1000
Describe in precise words what the function does
ANSWER:
- Modify the function slightly so that it returns the value:
$\sum_{i=1}^n e^{x_i}$
In other words, we want to write a function that calculates the sum of the exponential of each component of the input vector $x$.
Test your function with the argument vector: `x <- c(2,1,3,0.4)`. You should get an answer approximately equal to 31.6847 .
# add your own R code below this line
```
为了返回每个组件的指数之和,可以将函数 myfun() 修改如下:
myfun <- function(x) {
if (length(x) == 1) {
return(exp(x))
} else {
return(exp(x[1]) + myfun(x[-1]))
}
}
用输入向量 x <- c(2, 1, 3, 0.4) 来测试函数,我们应该得到一个大约等于 31.6847 的答案。
x <- c(2, 1, 3, 0.4)
sum_of_exp_x <- myfun(x)
print(sum_of_exp_x)