F#的新手,作为我的主要工具是R,我发现这些"较低级别"语言有点挑剔。我正在尝试编写递归函数(Cox-de Boor),给定输入向量x(数组或类似)返回相同长度的向量。其他参数是int,int和float []。到目前为止,我只设法为一个x做了。我很确定我的代码是愚蠢的,所以任何提示都会受到赞赏。
let rec basis (x:float) degree i (knots:float[]) =
let B=
match degree=0 with
|true -> if (x>=knots.[i-1] && x < knots.[i]) then 1.0 else 0.0
|false -> let Alpha1 =
match ((knots.[degree+i-1] - knots.[i-1])=0.0) with
|true -> 0.0
|false -> (x-knots.[i-1])/(knots.[degree+i-1]-knots.[i-1])
let Alpha2 =
match ((knots.[i+degree]-knots.[i])=0.0) with
|true-> 0.0
|false -> (knots.[i+degree]-x)/(knots.[i+degree]-knots.[i])
Alpha1*(basis x (degree-1) i knots) + Alpha2 * (basis x (degree-1) (i+1) knots)
B
干杯, 斯蒂
我试图复制的代码:
basis <- function(x, degree, i, knots) {
if(degree == 0){
B <- ifelse((x >= knots[i]) & (x < knots[i+1]), 1, 0)
}
else {
if((knots[degree+i] - knots[i]) == 0) {
alpha1 <- 0
}
else {
alpha1 <- (x - knots[i])/(knots[degree+i] - knots[i])
}
if((knots[i+degree+1] - knots[i+1]) == 0) {
alpha2 <- 0
} else {
alpha2 <- (knots[i+degree+1] - x)/(knots[i+degree+1] - knots[i+1])
}
B <- alpha1*basis(x, (degree-1), i, knots) + alpha2*basis(x, (degree-1), (i+1), knots)
}
return(B)
}
bs <- function(x, degree=3, interior.knots=NULL, intercept=FALSE, Boundary.knots = c(0,1)) {
if(missing(x)) stop("You must provide x")
if(degree < 1) stop("The spline degree must be at least 1")
Boundary.knots <- sort(Boundary.knots)
interior.knots.sorted <- NULL
if(!is.null(interior.knots)) interior.knots.sorted <- sort(interior.knots)
knots <- c(rep(Boundary.knots[1], (degree+1)), interior.knots.sorted,rep(Boundary.knots[2], (degree+1)))
K <- length(interior.knots) + degree + 1
B.mat <- matrix(0,length(x),K)
for(j in 1:K) B.mat[,j] <- basis(x, degree, j, knots)
if(any(x == Boundary.knots[2])) B.mat[x == Boundary.knots[2], K] <- 1
if(intercept == FALSE) {
return(B.mat[,-1])
} else {
return(B.mat)
}
}
答案 0 :(得分:2)
如果你想用多个x来调用基础,那么我会这样做:
首先将基础的签名更改为
let rec basis degree i (knots:float[]) (x:float)
为您想要的所有x调用它:
xs |> List.map (basis degree i knots)
如果所有其他事情都按预期工作,那么应该给你一个数组。这意味着我将所有的x和管道(|&gt;)带到函数List.map
。 List.map
接受一个函数和一个元素列表,并将该函数应用于列表中的所有元素,并返回一个新的列表,其中已应用该函数。