[R] Bug in parse; memory access test forgotten ?
Jean Coursol
coursol at cristal.math.u-psud.fr
Thu Jun 24 15:22:37 CEST 2004
I was exploring the polynom library with students:
library(polynom)
x <- polynomial()
z <- (1+x)^100
f <- as.function(z) # => Segmentation fault (with R-1.8.1 and R-1.9.0) !!!
Debugging at hand:
as.function.polynomial <- function (x, ...)
{
p <- x
horner <- function(p) {
a <- as.character(rev(unclass(p)))
h <- a[1]
while (length(a <- a[-1]) > 0) {
h <- paste("x*(", h, ")", sep = "")
if (a[1] != 0)
h <- paste(a[1], " + ", h, sep = "")
}
h
}
f <- function(x) NULL
body(f) <- parse(text = horner(p))[[1]]
f
}
horner <- function(p) {
a <- as.character(rev(unclass(p)))
h <- a[1]
while (length(a <- a[-1]) > 0) {
h <- paste("x*(", h, ")", sep = "")
if (a[1] != 0)
h <- paste(a[1], " + ", h, sep = "")
}
h
}
x <- polynomial()
z <- (1+x)^100
zh <- horner(z)
nchar(zh)
[1] 2404
parse(text = zh) # => Segmentation fault (it ran one time !!!)
# The R solution (VR S programming p 95)
as.function.polynomial <- function(p) {
function(x) { v <- 0; for (a in rev(p)) v <- a + x*v; v }
}
# is running perfectly...
Jean Coursol
More information about the R-help
mailing list