5.10 Random data generationPyxplot has functions for generating random numbers from a variety of common probability distributions. These functions are in the random module:
These functions all rely on a common underlying random number generator1, whose seed may be set using the set seed command, which should be followed by any integer. The sequence of random samples generated is always the same after setting any particular seed. When Pyxplot starts, the seed is implicitly set to zero. This means that Pyxplot always produces the same series of random numbers when restarted. This series can be reproduced by typing: set seed 0 For applications where this repeatability is undesirable, the following command may help, using the system clock as a random seed: set seed time.now().toUnix() This gives a different sequence of random numbers each second. However, the user is advised to consider carefully whether this is sufficient for the particular application being implemented. Example: Using random numbers to estimate the value of ![]() Pyxplot’s functions for generating random numbers are most commonly used for adding noise to artificially-generated data. In this example, however, we use them to implement a rather inefficient algorithm for estimating the value of the mathematical constant ![]() ![]() ![]() ![]() ![]() The following script performs this calculation using ![]() Nsamples = 500 rand() = random.random() set samp Nsamples set output "pi_estimation.dat" tabulate 1-2*rand():1-2*rand() using 0:2:3 n=0 foreach datum i,j in "pi_estimation.dat" u 2:3 { n = n + (hypot(i,j) ![]() } print "pi=%s"%(n / Nsamples * 4) On the author’s machine, this script returns a value of ![]() ![]() ![]() ![]() ![]() ![]() With a little modification, this script can be adapted to produce a diagram of the datapoints used in its calculation. Below is a modified version of the second half of the script, which loops over the data points stored in the data file random.dat. It uses Pyxplot’s vector graphics commands, which will be introduced in Chapter 10, to produce such a diagram: set multiplot ; set nodisplay # Draw a unit circle and a unit square title = "ex_pi_estimation" ; load "fig_init.ppl" box from -width/2,-width/2 to width/2,width/2 circle at 0,0 radius width/2 with lt 2 # Now plot the positions of these random data points andi # count how many lie within a unit circle n=0 foreach datum i,j in "pi_estimation.dat" using 2:3 { point at width/2*i , width/2*j with ps 0.1 n = n + (hypot(i,j) ![]() } set display ; refresh print "pi=%.4f"%(n / Nsamples * 4) The graphical output from this script is shown below. The number of datapoints has been reduced to Nsamples ![]() ![]() Footnotes
|