From 16ae765e1c9c2ce68125ba1d6b1ed18c5b8b3cf2 Mon Sep 17 00:00:00 2001 From: Jacob Patterson-Stein Date: Fri, 11 Oct 2024 21:34:56 -0400 Subject: [PATCH] Adding ACORN algo rng An initial attempt at implementing a simple ACORN random number generator --- src/acorn.cpp | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 src/acorn.cpp diff --git a/src/acorn.cpp b/src/acorn.cpp new file mode 100644 index 0000000..dea0494 --- /dev/null +++ b/src/acorn.cpp @@ -0,0 +1,60 @@ +#include +using namespace Rcpp; + +//' Additive Congruential Random Number (ACORN) Pseudorandom Number Generator + //' + //' The Additive Congruential Random Number (ACORN) pseudorandom number generator was developed in 1989 by R.S.Wikramaratna. + //' The ACORN algorithm is based on additive congruential methods, which use modular arithmetic combined with addition to evolve a sequence of random numbers. + //' The state is maintained in a vector {x} of length {k}, initialized with a seed. At each iteration, the state is updated through additive congruence. + //' + //' The generator operates as follows: + //' 1. Select an {n} value of numbers to generate. + //' 2. Set a {seed} for the algorithm. + //' 3. Choose a {k} value to set the order of the algorithm and determine how many additive steps occur. + //' 4. The result is derived from the last value in the state vector. + //' + //' @param seed Initial seed for the generator. This should be an integer. + //' @param n The number of random numbers to generate. + //' @param k The order of the ACORN algorithm, determining how many additive steps occur. + //' + //' @return A numeric vector of pseudorandom values generated by the ACORN algorithm. + //' + //' @references Wikramaratna, R.S. (1989). ACORN — A new method for generating sequences of uniformly distributed Pseudo-random Numbers. Journal of Computational Physics. 83. 16-31. + //' + //' @examples + //' # Example usage of the acorn_rng function + //' acorn_rng(10, seed = 123, k = 5) + + //' + // [[Rcpp::export]] + +NumericVector acorn_rng(int n, int seed, int k) { + NumericVector result(n); + + // Initialize state variables + std::vector x(k, seed); // Seed replicated across the vector + + // Generate random numbers + for (int i = 0; i < n; ++i) { + // Update the state vector + for (int j = k - 1; j > 0; --j) { + x[j] = x[j] + x[j - 1]; // Additive step + } + + // Modulo to ensure we stay within limits + x[0] = x[0] + 1; // Keep evolving the seed + long long random_value = x[k - 1]; // Use the last element as the random number + + // Store the random number in the result vector + result[i] = random_value % 1000000000; // Modulus to limit large numbers + } + + return result; +} + + + + +/*** R +acorn_rng(10, seed = 123, k = 5) +*/