6.4: Advanced Randomization Techinques
- Page ID
- 555727
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\dsum}{\displaystyle\sum\limits} \)
\( \newcommand{\dint}{\displaystyle\int\limits} \)
\( \newcommand{\dlim}{\displaystyle\lim\limits} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\(\newcommand{\longvect}{\overrightarrow}\)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\ket}[1]{\left| #1 \right>}\)
\(\newcommand{\bra}[1]{\left< #1 \right|}\)
\(\newcommand{\braket}[2]{\left< #1 \vphantom{#2} \right| \left. #2 \vphantom{#1} \right>}\)
\(\newcommand{\braopket}[3]{\left< #1 \vphantom{#2}\vphantom{#3} \right| #2 \vphantom{#1}\vphantom{#3} \left| #3 \vphantom{#1}\vphantom{#2} \right>}\)
\(\newcommand{\qmvec}[1]{\mathbf{\vec{#1}}}\)
\(\newcommand{\op}[1]{\hat{\mathbf{#1}}}\)
\(\newcommand{\expect}[1]{\langle #1 \rangle}\)
\(\newcommand{\dfn}[1]{\emph{\textbf{#1}}}\)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)
This page summarizes safer randomization patterns in the PG 2.17 subset. The goal is to avoid impossible values, repeated variants, and hard-to-reproduce failures.
Use this page when: you need multi-step randomization or constraints between values, or you want to choose the right randomization function for your situation. Randomization variables are typically defined in the Setup block (see Setup). For testing randomized variants, see Testing Randomization and Edge Cases.
Built-in random functions are already seeded
The PG environment automatically seeds the random number generator with $problemSeed before your problem code runs. For most problems, you can use the built-in random functions directly without any manual seeding. The same $problemSeed always produces the same sequence of random values, so student results are reproducible.
# These functions are already deterministic based on $problemSeed. # No manual seeding required for most problems. $value = random(1, 10, 1); $item = list_random(@items); $nonzero = non_zero_random(-5, 5, 1);
Core randomization functions (PGbasicmacros.pl)
| Function | What it does | When to use it |
|---|---|---|
random(begin, end, incr) |
Returns a random number from begin to end stepping by incr. | Numeric ranges like concentrations, volumes, or counts. |
non_zero_random(begin, end, incr) |
Same as random but excludes zero from the result. | Denominators, divisors, or any value that must not be zero. |
list_random(@list) |
Returns one randomly chosen element from the list. | Choosing from named items like enzymes, organisms, or codons. |
SRAND(seed) |
Resets the global PG random generator to a specific seed. | Rarely needed. The environment already seeds with problemSeed. |
Other randomization helpers
random_coprime([arrays...])andrandom_pairwise_coprime([arrays...])from PGauxiliaryFunctions.pl return coprime integers.randomOrder(...)in parserPopUp.pl and parserRadioButtons.pl shuffles answer choices.randomPrime(start, end)from contextInteger.pl returns a random prime in the given range.
Statistics distribution functions
These functions generate random samples from common probability distributions, useful for statistics and quantitative biology problems.
| Function | Distribution |
|---|---|
urand(mean, sd, N, digits) |
Normal distribution with given mean and standard deviation. |
exprand(lambda, N, digits) |
Exponential distribution with rate parameter lambda. |
poissonrand(lambda, N) |
Poisson distribution with rate parameter lambda. |
binomrand(p, N, num) |
Binomial distribution with probability p and N trials. |
bernoullirand(p, num, options) |
Bernoulli distribution (single trial, probability p). |
discreterand(n, @table) |
Discrete distribution from a probability table. |
Manual PGrandom: when and how
Most problems do not need a manual PGrandom object. Only create one when you need multiple independent random streams or explicit control over seeding for complex multi-stage randomization.
# CORRECT: create an instance, then call srand on the instance.
$local_random = PGrandom->new();
$local_random->srand($problemSeed);
# Use the instance methods for random values.
$value = $local_random->random(1, 10, 1);
$item = $local_random->list_random('A', 'B', 'C');
Common PGrandom mistakes
| Mistake | Why it fails |
|---|---|
PGrandom->seed($problemSeed) |
The method is called srand, not seed. |
PGrandom->srand($problemSeed) |
Cannot call srand as a class method. Create an instance with PGrandom->new() first. |
SRAND($problemSeed) |
Resets the global RNG. Usually unnecessary because it is already seeded. |
Practical tips
- Sort hash keys before random selection. Hash key order is not guaranteed in Perl. Always sort keys first so the same seed yields the same result across runs.
- Avoid NchooseK and shuffle. These are deprecated in the PG 2.17 subset. Use built-in random selection or manual array manipulation for subsets.
- Record the seed when debugging. Use
$problemSeedto reproduce failures exactly.
# Sort hash keys before selecting randomly. @sorted_keys = sort keys %hash; $selected = list_random(@sorted_keys);
Guard patterns
Always add guard checks so randomization never produces impossible cases.
Zero denominators
$den = random(1, 9, 1);
if ($den == 0) { $den = 1; }
$ratio = $num / $den;
Repeated values
$a = random(1, 10, 1);
do { $b = random(1, 10, 1); } until ($b != $a);
Invalid domains
# Ensure the argument to log is positive.
$conc = random(1, 100, 1);
if ($conc <= 0) { $conc = 1; }
$pH = -log($conc / 1000) / log(10);
Negative concentrations
$stock = random(10, 100, 5);
$dilution = random(2, 20, 1);
$final = $stock / $dilution;
if ($final < 0.1) {
$dilution = 2;
$final = $stock / $dilution;
}
Biology-specific randomization examples
Randomized dilution series
$stock_mM = random(10, 50, 5); $dilution_factor = list_random(2, 5, 10, 20); $final_uM = ($stock_mM * 1000) / $dilution_factor;
Randomized genetics cross
# Monohybrid cross with valid Mendelian ratios.
@dominant_traits = ('Tall', 'Round', 'Purple', 'Axial');
@recessive_traits = ('Short', 'Wrinkled', 'White', 'Terminal');
$idx = random(0, scalar(@dominant_traits) - 1, 1);
$dominant = $dominant_traits[$idx];
$recessive = $recessive_traits[$idx];
$total_offspring = random(40, 120, 4);
$expected_dominant = 3 * $total_offspring / 4;
$expected_recessive = $total_offspring / 4;
Randomized qPCR conditions
# qPCR problem with plausible Ct values and efficiency. $efficiency = random(90, 100, 1) / 100; $Ct_control = random(18, 25, 1); $fold_change = list_random(2, 4, 8, 16); $delta_Ct = -log($fold_change) / log(1 + $efficiency); $Ct_treated = $Ct_control + $delta_Ct;
Complete working example
Randomized genetics problem -- A full problem demonstrating random() and list_random() with biology content and a guard check to prevent repeated values.
## TITLE('Randomized genetics offspring count')
## DESCRIPTION
## Calculate the expected number of offspring showing the
## dominant phenotype from a randomized monohybrid cross.
## ENDDESCRIPTION
## KEYWORDS('genetics','randomization','numeric','list_random')
## DBsubject('Genetics')
## DBchapter('Mendelian Genetics')
## DBsection('Expected Ratios')
## Date('2026-02-15')
## Author('Author name')
## Institution('Institution name')
DOCUMENT();
loadMacros(
"PGstandard.pl",
"MathObjects.pl",
"PGML.pl",
"PGcourse.pl",
);
Context("Numeric");
@traits = ('Tall', 'Round', 'Purple', 'Axial');
$trait = list_random(@traits);
$total = random(40, 120, 4);
$expected_dom = Real(3 * $total / 4);
BEGIN_PGML
In a monohybrid cross between two heterozygous plants,
[$total] offspring are produced. The dominant trait is
"[$trait]".
How many offspring are expected to show the dominant
phenotype? [________]{$expected_dom}
END_PGML
ENDDOCUMENT();
Apply it today
- Use the built-in
random()functions for most problems. They are already seeded. - Only create a PGrandom instance when you need independent random streams.
- Add guard checks so randomization never produces impossible cases.
- Sort hash keys before random selection for deterministic results.


