RosettaCodeData/Task/Arithmetic-derivative/R/arithmetic-derivative.r

23 lines
524 B
R
Raw Permalink Normal View History

2024-07-13 15:19:22 -07:00
library(gmp) #for big number factorization
2026-04-30 12:34:36 -04:00
options(scipen=20)
2024-07-13 15:19:22 -07:00
2026-04-30 12:34:36 -04:00
arith_deriv <- function(x) {
2026-02-01 16:33:20 -08:00
if(x %in% c(0, 1, -1)) return(0)
n <- abs(x)
facs <- as.numeric(factorize(n))
nfacs <- length(facs)
2026-04-30 12:34:36 -04:00
if(nfacs == 1) return(sign(x))
2026-02-01 16:33:20 -08:00
d <- sum(facs[1:2])
2026-04-30 12:34:36 -04:00
if(nfacs > 2) {
2026-02-01 16:33:20 -08:00
c_prod <- cumprod(facs)
for(i in 3:nfacs) d <- d*facs[i]+c_prod[i-1]
2024-07-13 15:19:22 -07:00
}
2026-02-01 16:33:20 -08:00
sign(x)*d
2024-07-13 15:19:22 -07:00
}
2026-02-01 16:33:20 -08:00
t(matrix(sapply(-99:100, arith_deriv), nrow=10))
2024-07-13 15:19:22 -07:00
2026-02-01 16:33:20 -08:00
pows <- 10^(1:20)
derivs <- sapply(pows, arith_deriv)
writeLines(paste0("D(", pows, ")/7 = ", derivs/7))