Skip to content

Instantly share code, notes, and snippets.

@anna328p
Created February 10, 2020 00:17
Show Gist options
  • Save anna328p/b5f558400619e0b63457ab983fd717b1 to your computer and use it in GitHub Desktop.
Save anna328p/b5f558400619e0b63457ab983fd717b1 to your computer and use it in GitHub Desktop.
xorshift64 RNG implemented in Google Apps Script
function xor(state1, state2) {
var x = state1.slice()
x[0] ^= state2[0]
x[1] ^= state2[1]
return x
}
/*
state:
[ state[0] ][ state[1] ]
*/
function lshift(state, width) {
var x = state.slice()
topBits = state[1] >>> (32 - width)
x[1] <<= width
x[0] <<= width
x[0] |= topBits
return x
}
function rshift(state, width) {
var x = state.slice()
var bot = state[0]
bot << (32 - width)
x[0] >>>= width
x[1] >>>= width
x[1] &= bot
return x
}
function randgen(seed1, seed2, iter) {
var state = [seed1, seed2]
for (var i = 0; i < iter; i++) {
var x = state.slice()
x = xor(x, lshift(x, 13))
x = xor(x, rshift(x, 7))
x = xor(x, lshift(x, 17))
state = x.slice()
}
var res = Math.abs(state[0] * Math.pow(2, 32) + state[1])
return res / 10000
}
/**
* Generates a random number using the 64-bit XORSHIFT algorithm.
*
* @param {number} seed1 The first half of the seed.
* @param {number} seed2 The second half of the seed.
* @param {number} iter The iteration or range of iterations.
* @return The random number.
* @customfunction
*/
function RANDOMGEN(seed1, seed2, iter) {
if (iter.length) {
for (var i = 0; i < iter.length; i++) {
iter[i] = randgen(seed1, seed2, iter[i])
}
return iter
} else {
return randgen(seed1, seed2, iter)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment