N-fold derivative of p variables of a function fx(x1...xn)

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

N-fold derivative of p variables of a function fx(x1...xn)

Benjamin S
Hi everyone, I want to define a function that derives a function fx with n variables related to p variables. The problem is the function definition in the loop. Can anyone help me? Thank you very much...

###########Code###############


Partdiff<-function(x,fx,p){
  #x=vector of function imputs of fx(x)
  #fx= function for partial differentiation
  #p=vector of indices of variables in the order for differentiation e.g. c(1,1,2)=two times first, one time second

  numder<-function(x,gfunc,i){

    h=10^-5 #Delta for numerical differentation
   
    vec<-NULL #g(x+h)
   
    if(i>1){
    for(j in 1:(i-1)){
      vec[j]<-x[j]
    }
      }
    vec[i]<-x[i]+h
    if(i<length(x)){
    for(j in (i+1):length(x)){
      vec[j]<-x[j]
    }
    }
   
    vec2<-NULL #g(x-h)
    if(i>1){
      for(j in 1:(i-1)){
        vec2[j]<-x[j]
      }
    }
    vec2[i]<-x[i]-h
    if(i<length(x)){
      for(j in (i+1):length(x)){
        vec2[j]<-x[j]
      }
    }
 #central difference quotient
    return((gfunc(vec)-gfunc(vec2))/(2*h))
  }
 
 Partdiff <- list()  #list I will write the functions
 Partdiff[[1]] <- function(x){ numder(x,gfunc = fx,p[1])} #first differentation
 for(i in 2:length(p)){
   
   Partdiff[[i]] <- eval(substitute(
     function(x) numder(x,gfunc = functional,i=orders)), list(functional=(Partdiff[[i-1]](x)),orders=p[i]))

 }

return(Partdiff[[length(p)]](x))
}



f<-function(x){prod(sin(x))}

Partdiff(c(1,1,1),f,c(1,2,3)) #Exact: (cos(1))^3=0.1577...
Partdiff(c(0.1,0.2,0.3),f,c(1,1,3)) #Exact: -0.018947...


###########End Code############