n <- seq(1, 50, by=1/4)
st.n <- stirlerr(n) # now vectorized
stopifnot(identical(st.n, sapply(n, stirlerr)))
st3. <- stirlerr(n, "R3", direct.ver = "R3") # previous default
st3 <- stirlerr(n, "R3", direct.ver = "lgamma1p") # new? default
## for these n, there is *NO* difference:
stopifnot(st3 == st3.)
plot(n, st.n, type = "b", log="xy", ylab = "stirlerr(n)")
st4 <- stirlerr(n, "R4.4_0", verbose = TRUE) # verbose: give info on cases
## order = k = 1:20 terms in series approx:
k <- 1:20
stirlOrd <- sapply(k, function(k) stirlerr(n, order = k))
matlines(n, stirlOrd)
matplot(n, stirlOrd - st.n, type = "b", cex=1/2, ylim = c(-1,1)/10, log = "x",
main = substitute(list(stirlerr(n, order=k) ~~"error", k == 1:mK), list(mK = max(k))))
matplot(n, abs(stirlOrd - st.n), type = "b", cex=1/2, log = "xy",
main = "| stirlerr(n, order=k) error |")
mtext(paste("k =", deparse(k))) ; abline(h = 2^-(53:51), lty=3, lwd=1/2)
colnames(stirlOrd) <- paste0("k=", k)
stCn <- stirlerrC(n)
all.equal(st.n, stCn, tolerance = 0) # see 6.7447e-14
stopifnot(all.equal(st.n, stCn, tolerance = 1e-12))
stC2 <- stirlerrC(n, version = "R4..1")
stC4 <- stirlerrC(n, version = "R4.4_0")
## lgammacor(n) : only defined for n >= 10
lgcor <- lgammacor(n)
lgcor6 <- lgammacor(n, nalgm = 6) # more accurate?
all.equal(lgcor[n >= 10], st.n[n >= 10], tolerance=0)# .. rel.diff.: 4.687e-14
stopifnot(identical(is.na(lgcor), n < 10),
all.equal(lgcor[n >= 10],
st.n [n >= 10], tolerance = 1e-12))
## look at *relative* errors -- need "Rmpfr" for "truth" % Rmpfr / DPQmpfr in 'Suggests'
if(requireNamespace("Rmpfr") && requireNamespace("DPQmpfr")) {
## stirlerr(n) uses DPQmpfr::stirlerrM() automagically when n is
relErrV <- sfsmisc::relErrV; eaxis <- sfsmisc::eaxis
mpfr <- Rmpfr::mpfr; asNumeric <- Rmpfr::asNumeric
stM <- stirlerr(mpfr(n, 512))
relE <- asNumeric(relErrV(stM, cbind(st3, st4, stCn, stC4,
lgcor, lgcor6, stirlOrd)))
matplot(n, pmax(abs(relE),1e-20), type="o", cex=1/2, log="xy", ylim =c(8e-17, 0.1),
xaxt="n", yaxt="n", main = quote(abs(relErr(stirlerr(n)))))
## mark "lgcor*" -- lgammacor() particularly !
col.lgc <- adjustcolor(c(2,4), 2/3)
matlines(n, abs(relE[,c("lgcor","lgcor6")]), col=col.lgc, lwd=3)
lines(n, abs(relE[,"lgcor6"]), col=adjustcolor(4, 2/3), lwd=3)
eaxis(1, sub10=2); eaxis(2); abline(h = 2^-(53:51), lty=3, col=adjustcolor(1, 1/2))
axis(1, at=15, col=NA, line=-1); abline(v=c(10,15), lty=2, col=adjustcolor(1, 1/4))
legend("topright", legend=colnames(relE), cex = 3/4,
col=1:6, lty=1:5, pch= c(1L:9L, 0L, letters)[seq_len(ncol(relE))])
legend("topright", legend=colnames(relE)[1:6], cex = 3/4, lty=1:5, lwd=3,
col=c(rep(NA,4), col.lgc), bty="n")
## Note that lgammacor(x) {default, n=5} is clearly inferior,
## but lgammacor(x, 6) is really good {in [10, 50] at least}
}# end if( )
Run the code above in your browser using DataLab