# Tips for WeBWorK Authors: Randomization

Producing random quantities in a WeBWorK problem.

## The Basic Method

Pick a random integer between 2 and 5 (inclusive), and put it in the variable $a1: An integer between 2 and 5 $a1 = random(2,5);


Pick a random number between 2 and 5 using steps of 0.1, and put it in the variable $a2: A number between 2 and 5, step size of 0.1 $a2 = random(2, 5, 0.1);


Pick a random integer between -2 and 5, but exclude zero (which might cause errors in the problem):

A non-zero integer between -2 and 5
$a3 = non_zero_random(-2,5);  ## Fancier Randomization Suppose we have already picked one number, $a, and now we want to pick $b so that it is between 1 to 10 but not equal to $a. The basic form is:

do { $b = random(1, 10); } until ($b != $a);  This will keep picking random numbers until we have one we like. The condition in the until clause can contain more than one comparison. Pick$c different from both $a and$b
do { $b = random(1, 10); } until (($c != $a) and ($c != $b));  ### Picking from a list Sometimes, you might want to pick from a list of numbers. $a = list_random(3, 4, 6, 9, 15, 18);


## Connected variables

It may happen that, in a problem, several variables are connected. Using a single random parameter, the values of several variables can be selected. Here is an example where three variables, element, atomic weight - mantissa, and atomic weight - exponent are linked.

Using lists to select connected variables
@element = ('Carbon','Silicon','Phosphorous','Sulfur','Gallium','Germanium','Arsenic','Gold');
@ma = ('2.00','4.68','5.18','5.34','1.17','1.22','1.25','3.29');
@mb = ('-26','-26','-26','-26','-25','-25','-25','-25',);
$n = random(0,7,1)  Now $n can be used as an index for the arrays and we can write problem statements such as:

BEGIN_PGML
you inject *singly charged negative [$element[$n]] ions,
that become positively charged [$nplus] times in the center of the accelerator*. The mass of a [$element[$n]] ion is [m = [$ma[$n]] \times 10^{[$mb[\$n]]}] kg.