【发布时间】:2017-05-04 21:11:56
【问题描述】:
我正在查看这个简短文档中的最后一个示例:
https://www.rdocumentation.org/packages/chebpol/versions/1.3-952/topics/mlappx
转载于此,
require(chebpol)
## evenly spaced grid-points
su <- seq(0,1,length.out=10)
## irregularly spaced grid-points
s <- su^3
## create approximation on the irregularly spaced grid
ml1 <- Vectorize(mlappx(exp,list(s)))
## test it, since exp is convex, the linear approximation lies above
## the exp between the grid points
ml1(su) - exp(su)
## multi linear approx
f <- function(x) exp(sum(x^2))
grid <- list(s,su)
ml2 <- mlappx(evalongrid(f,grid=grid),grid)
# an equivalent would be ml2 <- mlappx(f,grid)
a <- runif(2); ml2(a); f(a)
# we also get an approximation outside of the domain, of disputable quality
ml2(c(1,2)); f(c(1,2))
最后一行计算点 (1,2) 的 f 的近似值(通过线性插值)。如果我们使用以下方法进行矢量化,那么让它评估多对点的语法是什么:
ml2 <- Vectorize(mlappx(evalongrid(f,grid=grid),grid))
【问题讨论】:
-
Vectorize的语法是vF <- Vectorize(F),其中F是一个(标量)函数。您不需要包含的参数等。然后您可以像使用F一样使用vF。 -
@AndrewGustar 你能告诉我如何在上面的例子中让 ml2 评估两对点 (.5,.5) 和 (1,2) 吗?
-
或许
sapply(list(c(.5,.5),c(1,2)),ml2)
标签: r function syntax vectorization interpolation