Skip to content

Instantly share code, notes, and snippets.

@aperezdc
Created September 18, 2013 16:15
Show Gist options
  • Save aperezdc/6611580 to your computer and use it in GitHub Desktop.
Save aperezdc/6611580 to your computer and use it in GitHub Desktop.
RAND31 random number generator in D. Suitable for generating white noise for audio applications.
/*
* rand31.d
* Copyright (C) 2013 Adrian Perez <[email protected]>
*
* Implements the rand31 random number generation algorithm, which is
* particularly suitable for use as white noise for sound applications.
*
* For more information on the algorithm, please refer to:
* http://www.firstpr.com.au/dsp/rand31/
*
* Distributed under terms of the MIT license.
*/
module rand31;
private const constapmc = 16807;
long seed = 1;
ulong next() {
ulong lo = constapmc * (seed & 0xFFFF);
ulong hi = constapmc * (seed >> 16);
lo += (hi & 0x7FFF) << 16;
lo += hi >> 15;
if (lo > 0x7FFFFFFF) lo -= 0x7FFFFFFF;
return (seed = cast(long) lo);
}
double nextf() {
return next() / 2147483647.0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment