g1 <- function(u) 1/gamma(u+1) - 1
u <- seq(-.5, 1.5, by=1/16); set.seed(1); u <- sample(u) # permuted (to check logic)
g11 <- vapply(u, gam1d, 1)
gam1d. <- gam1d(u)
stopifnot( all.equal(g1(u), g11) )
stopifnot( identical(g11, gam1d.) )
## Comparison of g1() and gam1d(), slightly extending the [-.5, 1.5] interval:
u <- seq(-0.525, 1.525, length.out = 2001)
mg1 <- cbind(g1 = g1(u), gam1d = gam1d(u))
clr <- adjustcolor(1:2, 1/2)
matplot(u, mg1, type = "l", lty = 1, lwd=1:2, col=clr) # *no* visual difference
## now look at *relative* errors
relErrV <- sfsmisc::relErrV
relE <- relErrV(mg1[,"gam1d"], mg1[,"g1"])
plot(u, relE, type = "l")
plot(u, abs(relE), type = "l", log = "y",
main = "|rel.diff| gam1d() vs 'direct' 1/gamma(u+1) - 1")
## now {Rmpfr} for "truth" :
if(requireNamespace("Rmpfr")) withAutoprint({
asN <- Rmpfr::asNumeric; mpfr <- Rmpfr::mpfr
gam1M <- g1(mpfr(u, 512)) # "cheap": high precision avoiding "all" cancellation
relE <- asN(relErrV(gam1M, gam1d(u)))
plot(relE ~ u, type="l", ylim = c(-1,1) * 2.5e-15,
main = expression("Relative Error of " ~~ gam1d(u) %~~% frac(1, Gamma(u+1)) - 1))
grid(lty = 3); abline(v = c(-.5, 1.5), col = adjustcolor(4, 1/2), lty=2, lwd=2)
})
if(requireNamespace("Rmpfr") && FALSE) {
## Comparison using Rmpfr; slightly extending the [-.5, 1.5] interval:
## {relErrV(), mpfr(), asN() defined above}
u <- seq(-0.525, 1.525, length.out = 2001)
gam1M <- gam1(mpfr(u, 128))
relE <- asN(relErrV(gam1M, gam1d(u)))
plot(relE ~ u, type="l", ylim = c(-1,1) * 2.5e-15,
main = expression("Relative Error of " ~~ gam1d(u) == frac(1, Gamma(u+1)) - 1))
grid(lty = 3); abline(v = c(-.5, 1.5), col = adjustcolor(4, 1/2), lty=2, lwd=2)
## what about the direct formula -- how bad is it really ?
relED <- asN(relErrV(gam1M, g1(u)))
plot(relE ~ u, type="l", ylim = c(-1,1) * 1e-14,
main = expression("Relative Error of " ~~ gam1d(u) == frac(1, Gamma(u+1)) - 1))
lines(relED ~ u, col = adjustcolor(2, 1/2), lwd = 2)
# mtext("comparing with direct formula 1/gamma(u+1) - 1")
legend("top", c("gam1d(u)", "1/gamma(u+1) - 1"), col = 1:2, lwd=1:2, bty="n")
## direct is clearly *worse* , but not catastrophical
}
Run the code above in your browser using DataLab