多数情况下,在R语言里,<- 与= 两个都是赋值的意思,没有区别,比如
>x<- c(1:5)x
[1] 1 2 3 4 5
>x=c(1:10)x
[1] 1 2 3 4 5 6 7 8 9 10
只有在有些时候会有区别,比如
>x<- c(1:5)x
[1] 1 2 3 4 5
>length(x=c(1:10))x
[1] 10
[1] 1 2 3 4 5
>length(x<- c(1:10))x
[1] 10
[1] 1 2 3 4 5 6 7 8 9 10
为了防止出错,在R里面赋值最好使用符号 <-
LagrangePolynomial <- function(x,y) {len = length(x)
if(len != length(y))
stop("length not equal!")
if(len < 2)
stop("dim size must more than 1")
#pretreat data abd alloc memery
xx <- paste("(","a -",x,")")
m <- c(rep(0,len))
#combin express
for(i in 1:len) {
td <- 1
tm <- "1"
for(j in 1:len) {
if(i != j) {
td <- td*(x[i] - x[j])
tm <- paste(tm,"*",xx[j])
}
}
tm <- paste(tm,"/",td)
m[i]<-tm #m[i] <- parse(text=tm)
}
#combin the exrpession
m <- paste(m,"*",y)
r <- paste(m,collapse="+")
#combin the function
fbody <- paste("{ return(",r,")}")
f <- function(a) {}
#fill the function's body
body(f) <- parse(text=fbody)
return(f)
}
这是拉格朗日多项式插值算法 你参考下吧