Random numbers in strongly pure functions
bearophile
bearophileHUGS at lycos.com
Mon Nov 22 04:36:46 PST 2010
Hopefully I am not the only person that is using the "pure" attribute :-)
I have felt the need to generate random numbers in pure functions too, so I have suggested to add to the std.random module a strongly pure function that takes a seed (and other arguments) and returns the next seed (and optionally a ranged value too).
An example:
import std.stdio: writeln;
immutable struct rndPair {
double seed, rnd;
}
// strongly pure
// Probably with DMD 2.050 a std.typecons.Tuple can't
// be used as return value here
pure nothrow rndPair nextRandom(const double seed, const double max) {
enum int IA = 3_877, IC = 29_573, IM = 139_968;
immutable double new_seed = (seed * IA + IC) % IM;
return rndPair(new_seed, max * (new_seed * (1.0 / IM)));
}
// strongly pure
pure double[] foo(const int n, const double firstSeed=42) {
double seed = firstSeed;
auto res = new double[n];
foreach (ref r; res) {
auto seed_rnd = nextRandom(seed, 1.0);
r = seed_rnd.rnd;
seed = seed_rnd.seed;
}
return res;
}
void main() {
writeln(foo(5));
// Output:
// [0.37465, 0.729024, 0.636467, 0.793481, 0.538545]
}
For a better example and more info click here:
http://d.puremagic.com/issues/show_bug.cgi?id=5249
Bye,
bearophile
More information about the Digitalmars-d
mailing list