Вопрос

Here's the latex code for the function that I would like to expand and derive:

$f(x) = \sum\limits_{i=1}^n \left(x_i + \frac{h}{2}(1-ih)\sum\limits_{j=1}^i jh(x_j + jh +1)^3 + \frac{h}{2}ih\sum\limits_{j=i+1}^n (1-jh)(x_j+jh+1)^3 \right)^2$

enter image description here

I plan deriving for n=6 through deriv(expression(myfunction),c('x1', 'x2','x3','x4','x5','x6')). I don't know how to compute the derivative without expanding the function but if there is a way please let me know.

My problem begins when trying to expand the function in just one string because part of the expression gets repeated so any help would be appreciated:

n<-6
myexpr <- sapply(1:n, function(i) paste( paste('x',i,sep=''),paste('+h/2*(1-',i,'*h)*(',sep=''),
                           sapply(1:i,function(j) paste('(j*h*(',paste('x',j,sep=''),'j*h+1)^3)',collapse='+')),
                           paste('+h/2*',i,'*h*(',sep=''),
                           sapply((i+1):n,function(j) paste('((1-j*h)*(',paste('x',j,sep=''),'+j*h+1)^3)',collapse='+'))
                           ,collapse='+'))


deriv(expression(myexpr),c('x1', 'x2','x3','x4','x5','x6'))
Это было полезно?

Решение 2

I've been down voted for something I though that could be done. In fact, it is not only that could be done but also that R solves very fast:

z <- paste(
  sapply(1:6, function(i,n=6) {

    require(MASS)
    h <- fractions(1/(n+1))

    a <- paste('x',i,sep='')
    b <- paste('+.5*',h,'*(1-',i,'*',h,')*(',sep='')
    cc <- paste(sapply(1:i,function(j) paste(j,'*',h,'*(',paste('x',j,sep=''),'+',j,'*',h,'+1)^3',sep='')),collapse='+')
    d <- paste(a,b,cc,')')

    e <- if (i < 6) paste('+.5*',h,'*(',i,'*',h,')*(',sep='') else ''
    f <- if (i < 6) paste(sapply((i+1):n,function(j) paste('(1-',j,'*',h,')*(',paste('x',j,sep=''),'+',j,'*',h,'+1)^3',sep='')),collapse='+') else ''
    g <- paste(e,f,ifelse(i!=6,')',""))

    paste('(',d,g,')^2',sep='')

  }
  ),
  collapse='+')

deriv(parse(text=z),c('x1','x2','x3','x4','x5','x6'))

Другие советы

I think you should try something simpler to get a handle on working with expressions. In your case I am able to find an error in your construction of this (ridiculously large) expression by simply looking at the first argument.

> do.call(deriv, list(expr=parse(text=myexpr[1]), namevec=c('x1') ) )
Error in parse(text = myexpr[1]) : <text>:1:31: unexpected symbol
1: x1 +h*0.5*(1-1*h)*( (j*h*( x1 j
                                  ^
> substr(myexpr[1],1,40)
[1] "x1 +h*0.5*(1-1*h)*( (j*h*( x1 j*h+1)^3) "

So you are missing a "+"-sign in the expansion of the second term.

Strategically, however, I would ahve thought that Mathematica or Maxima would be better platforms to use for this purpose.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top