Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions src/acorn.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#include <Rcpp.h>
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<long long> 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)
*/