Random Numbers
bearophile
bearophileHUGS at lycos.com
Sat Aug 4 10:02:18 PDT 2012
Ralph Main:
> The module std.random documentation doesn't work as per the
> examples.
> The example shows getting a random number by the following code
> does not work:
>
> <code>
> // Generate a uniformly-distributed integer in the range
> [0, 14]
> auto i = uniform(0, 15);
> // Generate a uniformly-distributed real in the range [0,
> 100)
> // using a specific random generator
> Random gen;
> auto r = uniform(0.0L, 100.0L, gen);
> </code>
>
> <code>
> // Gets a random number
> int get_random() {
> auto rng = new Random(unpredictableSeed);
> auto rn = uniform(0, m_files.length, rng);
> return rn;
> }
> </code>
This code works, but it's a bad idea to create a new generator
inside getRandom():
import std.stdio, std.random;
// Gets a random number, badly
int getRandom(int m) {
auto rng = new Random(unpredictableSeed);
return uniform(0, m, rng);
}
void main() {
// Generate a uniformly-distributed integer in the range [0,
14]
auto i = uniform(0, 15);
// Generate a uniformly-distributed real in the range [0, 100)
// using a specific random generator
Random gen;
auto r = uniform(0.0L, 100.0L, gen);
writeln(r);
writeln(getRandom(10));
}
> The new keyword was not in the example, and the original
> example code would not work. When looking at the source code
> of the std libraries, a struct can contain a constructor, so
> therefore it is similar to a class; and on a whim I tried the
> new keyword. So I thought I would pass this information along.
> I looked at other posts in the forum, but didn't see anyone
> using the new keyword. Is this a bug, or a change to the D
> language implementation?
In D you instantiate a class with new, it generally gets
allocated on the heap, and what you obtain is a class reference,
that is a kind of pointer.
Structs can be allocated with new, usually on the heap, and you
get a pointer to a struct. Or they can be created locally without
"new", often on the stack or inside another struct/class
instance, and what you obtain is a struct value.
std.random.Random is a struct.
std.random.uniform() as third optional value seems to accept both
a struct pointer and a struct (that it takes by reference, so
using a pointer adds another indirection level, and this is not
good. I don't know if the D compiler is able to remove this extra
indirection level).
Are my answers enough?
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list