View source code
Display the source code in std/random.d from which this
page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a
Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.
Requires a signed-in GitHub account. This works well for small changes.
If you'd like to make larger changes you may want to consider using
local clone.
Function std.random.dice
Rolls a dice with relative probabilities stored in proportions
. Returns the index in proportions
that was chosen.
{null} dice(Rng, Num)()
if (isNumeric!Num && isForwardRange!Rng);
size_t dice(R, Range)
(
ref R rnd,
Range proportions
)
if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range);
size_t dice(Range)
(
Range proportions
)
if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range);
{null} dice(Num)()
if (isNumeric!Num);
Parameters
Name | Description |
---|---|
rnd | (optional) random number generator to use; if not
specified, defaults to rndGen |
proportions | forward range or list of individual values whose elements correspond to the probabilities with which to choose the corresponding index value |
Returns
Random variate drawn from the index values
[0, ... proportions
- 1], with the probability
of getting an individual index value i
being proportional to
proportions[i]
.
Example
auto x = dice(0.5, 0.5); // x is 0 or 1 in equal proportions
auto y = dice(50, 50); // y is 0 or 1 in equal proportions
auto z = dice(70, 20, 10); // z is 0 70% of the time, 1 20% of the time,
// and 2 10% of the time
Example
auto rnd = MinstdRand0(42);
auto z = rnd .dice(70, 20, 10);
writeln(z); // 0
z = rnd .dice(30, 20, 40, 10);
writeln(z); // 2
Example
auto rnd = Xorshift(123_456_789);
auto i = dice(rnd, 0.0, 100.0);
writeln(i); // 1
i = dice(rnd, 100.0, 0.0);
writeln(i); // 0
i = dice(100U, 0U);
writeln(i); // 0
Authors
Andrei Alexandrescu Masahiro Nakagawa (Xorshift random generator) Joseph Rushton Wakeling (Algorithm D for random sampling) Ilya Yaroshenko (Mersenne Twister implementation, adapted from mir-random)
License
Copyright © 1999-2024 by the D Language Foundation | Page generated by ddox.