R Under development (unstable) (2024-10-17 r87242 ucrt) -- "Unsuffered Consequences" Copyright (C) 2024 The R Foundation for Statistical Computing Platform: x86_64-w64-mingw32/x64 R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > library(randtoolbox) Loading required package: rngWELL This is randtoolbox. For an overview, type 'help("randtoolbox")'. > > #compare two implementations > > f <- function(n) + { + res <- numeric(n+1) + res[1:2] <- c(0,1) + + for(i in 1:(n-1)) + { + # i <- 1 + k <- 1:(i+1) -1 + res[1:(i+2)] <- c(k * res[1:(i+1)], 0) + c(0, res[1:(i+1)]) + } + res + } > > g <- function(n) + { + if( n == 0) + res <- 1 + if(n > 0) + res <- c(0,1) + + if(n > 1) + { + for(i in 1:(n-1)) + { + k <- 1:length(res) -1 + res <- c(k * res, 0) + c(0, res) + } + } + return(res) + } > > cbind(stirling(3) , f(3)) [,1] [,2] [1,] 0 0 [2,] 1 1 [3,] 3 3 [4,] 1 1 > cbind(stirling(4) , f(4)) [,1] [,2] [1,] 0 0 [2,] 1 1 [3,] 7 7 [4,] 6 6 [5,] 1 1 > > if(FALSE) + { + cbind(stirling(10) , f(10)) + cbind(stirling(12) , f(12)) + + system.time(f(2000)) + system.time(stirling(2000)) + + # library(microbenchmark) + # microbenchmark(f(1000), g(1000)) + # microbenchmark(f(2000), g(2000)) + + } > > proc.time() user system elapsed 0.21 0.12 0.34