俩地方,一个是这里:
td <- td*(x - x[j])
tm <- paste(tm,"*",xx[j])
还有就是:
tm <- paste(tm,"/",td)
m<-tm #m <- parse(text=tm)
最后就是这样的啦——
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 - x[j])
tm <- paste(tm,"*",xx[j])
}
}
tm <- paste(tm,"/",td)
m<-tm #m <- 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)
}
a = 4:6
b = c(10, 5.25, 1)
f <- LagrangePolynomial(a,b)
f(18)
要等于-11,就是这个样子啦
看瞎了快...