sfsmisc (version 1.1-17)

polyn.eval: Evaluate Polynomials

Description

Evaluate one or several univariate polynomials at several locations, i.e. compute coef[1] + coef[2]*x + ... + coef[p+1]* x^p (in the simplest case where x is scalar and coef a vector).

Usage

polyn.eval(coef, x)

Value

numeric vector or array, depending on input dimensionalities, see above.

Arguments

coef

“numeric” vector or matrix. If a vector, x can be an array and the result matches x.
If coef is a matrix it specifies several polynomials of the same degree as rows, x must be a vector, coef[,k] is for \(x^{k-1}\) and the result is a matrix of dimension length(x) * nrow(coef).

Note that coef can also be complex or bigrational (as.bigq(.) from gmp, or arbitrary precision ("mpfr") from Rmpfr, or similar number-like objects for which basic arithmetic is defined.

x

“numeric” vector or array. Either x or coef must be a vector.

Author

Martin Maechler, ages ago.

Details

The stable “Horner rule” is used for evaluation in any case.

See Also

For much more sophisticated handling of polynomials, use the polynom package, see, e.g., predict.polynomial. For multivariate polynomials (and also for nice interface to the orthopolynom package), consider the mpoly package.

Examples

Run this code
polyn.eval(c(1,-2,1), x = 0:3)# (x - 1)^2
polyn.eval(c(0, 24, -50, 35, -10, 1), x = matrix(0:5, 2,3))# 5 zeros!
(cf <- rbind(diag(3), c(1,-2,1)))
polyn.eval(cf, 0:5)

x  <- seq(-3,7, by=1/4)
cf <- 4:1
(px <- polyn.eval(cf, x)) # is exact
if((gmpT <-"package:gmp" %in% search()) || require("gmp")) withAutoprint({
 pxq <- polyn.eval(coef = as.bigq(cf, 1), x=x)
 pxq
 stopifnot(pxq == px)
 if(!gmpT) detach("package:gmp")
})

if((RmpfrT <-"package:Rmpfr" %in% search()) || require("Rmpfr")) withAutoprint({
 pxM <- polyn.eval(coef = mpfr(cf, 80), x=x) # 80 bits accuracy
 pxM
 stopifnot(pxM == px)
 if(!RmpfrT) detach("package:Rmpfr")
})

Run the code above in your browser using DataLab