Function for polynomials of arbitrary order (symbolic method preferred)

后端 未结 3 1317
鱼传尺愫
鱼传尺愫 2020-12-11 05:01

I\'ve found polynomial coefficients from my data:

R <- c(0.256,0.512,0.768,1.024,1.28,1.437,1.594,1.72,1.846,1.972,2.098,2.4029)
Ic <- c(1.78,1.71,1.57         


        
3条回答
  •  半阙折子戏
    2020-12-11 06:03

    Since my final solution with symbolic derivatives eventually goes too long, I use a separate session for numerical calculations. We can do this as for polynomials, derivatives are explicitly known so we can code them. Note, there will be no use of R expression here; everything is done directly by using functions.

    So we first generate polynomial basis from degree 0 to degree p - n, then multiply coefficient and factorial multiplier. It is more convenient to use outer than poly here.

    ## use `outer`
    g <- function (x, pc, nderiv = 0L) {
      ## check missing aruments
      if (missing(x) || missing(pc)) stop ("arguments missing with no default!")
      ## polynomial order p
      p <- length(pc) - 1L
      ## number of derivatives
      n <- nderiv
      ## earlier return?
      if (n > p) return(rep.int(0, length(x)))
      ## polynomial basis from degree 0 to degree `(p - n)`
      X <- outer(x, 0:(p - n), FUN = "^")
      ## initial coefficients
      ## the additional `+ 1L` is because R vector starts from index 1 not 0
      beta <- pc[n:p + 1L]
      ## factorial multiplier
      beta <- beta * factorial(n:p) / factorial(0:(p - n))
      ## matrix vector multiplication
      drop(X %*% beta)
      }
    

    We still use the example x and pc defined in the symbolic solution:

    x <- seq(0, 1, by = 0.2)
    pc <- 1:4 / 10
    
    g(x, pc, 0)
    # [1] 0.1000 0.1552 0.2536 0.4144 0.6568 1.0000
    
    g(x, pc, 1)
    # [1] 0.200 0.368 0.632 0.992 1.448 2.000
    
    g(x, pc, 2)
    # [1] 0.60 1.08 1.56 2.04 2.52 3.00
    
    g(x, pc, 3)
    # [1] 2.4 2.4 2.4 2.4 2.4 2.4
    
    g(x, pc, 4)
    # [1] 0 0 0 0 0 0
    

    The result is consistent with what we have with FUN in the the symbolic solution.

    Similarly, we can plot g using curve:

    curve(g(x, pc), from = 0, to = 5)
    curve(g(x, pc, 1), from = 0, to = 5, col = 2, add = TRUE)
    curve(g(x, pc, 2), from = 0, to = 5, col = 3, add = TRUE)
    curve(g(x, pc, 3), from = 0, to = 5, col = 4, add = TRUE)
    

提交回复
热议问题