Function for polynomials of arbitrary order (symbolic method preferred)

后端 未结 3 1319
鱼传尺愫
鱼传尺愫 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 05:37

    Now after quite much effort in demonstrating how we can work out this question ourselves, consider using R package polynom. As a small package, it aims at implementing construction, derivatives, integration, arithmetic and roots-finding of univariate polynomials. This package is written completely with R language, without any compiled code.

    ## install.packages("polynom")
    library(polynom)
    

    We still consider the cubic polynomial example used before.

    pc <- 1:4 / 10
    
    ## step 1: making a "polynomial" object as preparation
    pcpoly <- polynomial(pc)
    #0.1 + 0.2*x + 0.3*x^2 + 0.4*x^3 
    
    ## step 2: compute derivative
    expr <- deriv(pcpoly)
    
    ## step 3: convert to function
    g1 <- as.function(expr)
    
    #function (x) 
    #{
    #    w <- 0
    #    w <- 1.2 + x * w
    #    w <- 0.6 + x * w
    #    w <- 0.2 + x * w
    #    w
    #}
    #
    

    Note, by step-by-step construction, the resulting function has all parameters inside. It only requires a single argument for x value. In contrast, functions in the other two answers will take coefficients and derivative order as mandatory arguments, too. We can call this function

    g1(seq(0, 1, 0.2))
    # [1] 0.200 0.368 0.632 0.992 1.448 2.000
    

    To produce the same graph we see in other two answers, we get other derivatives as well:

    g0 <- as.function(pcpoly)  ## original polynomial
    
    ## second derivative
    expr <- deriv(expr)
    g2 <- as.function(expr)
    #function (x) 
    #{
    #    w <- 0
    #    w <- 2.4 + x * w
    #    w <- 0.6 + x * w
    #    w
    #}
    #
    
    ## third derivative
    expr <- deriv(expr)
    g3 <- as.function(expr)
    #function (x) 
    #{
    #    w <- 0
    #    w <- 2.4 + x * w
    #    w
    #}
    #
    

    Perhaps you have already noticed that I did not specify nderiv, but recursively take 1 derivative at a time. This may be a disadvantage of this package. It does not facilitate higher order derivatives.

    Now we can make a plot

    ## As mentioned, `g0` to `g3` are parameter-free
    curve(g0(x), from = 0, to = 5)
    curve(g1(x), add = TRUE, col = 2)
    curve(g2(x), add = TRUE, col = 3)
    curve(g3(x), add = TRUE, col = 4)
    

提交回复
热议问题