Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Main Content

Generating Pseudorandom Numbers

Pseudorandom numbers are generated by deterministic algorithms. They are "random" in the sense that, on average, they pass statistical tests regarding their distribution and correlation. They differ from true random numbers in that they are generated by an algorithm, rather than a truly random process.

Random number generators (RNGs) like those in MATLAB® are algorithms for generating pseudorandom numbers with a specified distribution.

For more information on the GUI for generating random numbers from supported distributions, seerandtool.

For more complex probability distributions, you can use the methods described inRepresenting Sampling Distributions Using Markov Chain Samplers.

Common Pseudorandom Number Generation Methods

Methods for generating pseudorandom numbers usually start with uniform random numbers, like the MATLABrand function produces. The methods described in this section detail how to produce random numbers from other distributions.

Direct Methods

Direct methods directly use the definition of the distribution.

For example, consider binomial random numbers. A binomial random number is the number of heads inN tosses of a coin with probabilityp of a heads on any single toss. If you generateN uniform random numbers on the interval(0,1) and count the number less thanp, then the count is a binomial random number with parametersN andp.

This function is a simple implementation of a binomial RNG using the direct approach:

function X = directbinornd(N,p,m,n)    X = zeros(m,n);% Preallocate memoryfor i = 1:m*n        u = rand(N,1);        X(i) = sum(u < p);endend

For example:

rng('default')% For reproducibilityX = directbinornd(100,0.3,1e4,1);histogram(X,101)

Figure contains an axes object. The axes object contains an object of type histogram.

Thebinornd function uses a modified direct method, based on the definition of a binomial random variable as the sum of Bernoulli random variables.

You can easily convert the previous method to a random number generator for the Poisson distribution with parameterλ. ThePoisson Distribution is the limiting case of the binomial distribution asN approaches infinity,p approaches zero, andNp is held fixed atλ. To generate Poisson random numbers, create a version of the previous generator that inputsλ rather thanN andp, and internally setsN to some large number andp toλ/N.

Thepoissrnd function actually uses two direct methods:

  • A waiting time method for small values ofλ

  • A method due to Ahrens and Dieter for larger values ofλ

Inversion Methods

Inversion methods are based on the observation that continuous cumulative distribution functions (cdfs) range uniformly over the interval(0,1). Ifu is a uniform random number on(0,1), then usingX=F-1(U) generates a random numberX from a continuous distribution with specified cdfF.

For example, the following code generates random numbers from a specificExponential Distribution using the inverse cdf and the MATLAB® uniform random number generatorrand:

rng('default')% For reproducibilitymu = 1;X = expinv(rand(1e4,1),mu);

Compare the distribution of the generated random numbers to the pdf of the specified exponential.

numbins = 50;h = histogram(X,numbins,'Normalization','pdf');holdonx = linspace(h.BinEdges(1),h.BinEdges(end));y = exppdf(x,mu);plot(x,y,'LineWidth',2)holdoff

Figure contains an axes object. The axes object contains 2 objects of type histogram, line.

Inversion methods also work for discrete distributions. To generate a random numberX from a discrete distribution with probability mass vectorP(X=xi)=pi wherex0<x1<x2<..., generate a uniform random numberu on(0,1) and then setX=xi ifF(xi-1)<u<F(xi).

For example, the following function implements an inversion method for a discrete distribution with probability mass vectorp:

function X = discreteinvrnd(p,m,n)    X = zeros(m,n);% Preallocate memoryfor i = 1:m*n        u = rand;        I = find(u < cumsum(p));        X(i) = min(I);endend

Use the function to generate random numbers from any discrete distribution.

p = [0.1 0.2 0.3 0.2 0.1 0.1];% Probability mass function (pmf) valuesX = discreteinvrnd(p,1e4,1);

Alternatively, you can use thediscretize function to generate discrete random numbers.

X = discretize(rand(1e4,1),[0 cusmsum(p)]);

Plot the histogram of the generated random numbers, and confirm then the distribution follows the specified pmf values.

histogram(categorical(X),'Normalization','probability')

Figure contains an axes object. The axes object contains an object of type categoricalhistogram.

Acceptance-Rejection Methods

The functional form of some distributions makes it difficult or time-consuming to generate random numbers using direct or inversion methods. Acceptance-rejection methods provide an alternative in these cases.

Acceptance-rejection methods begin with uniform random numbers, but require an additional random number generator. If your goal is to generate a random number from a continuous distribution with pdff, acceptance-rejection methods first generate a random number from a continuous distribution with pdfg satisfyingf(x)cg(x) for somec and allx.

A continuous acceptance-rejection RNG proceeds as follows:

  1. Chooses a densityg.

  2. Finds a constantc such thatf(x)/g(x)c for allx.

  3. Generates a uniform random numberu.

  4. Generates a random numberv fromg.

  5. Ifcuf(v)/g(v), accepts and returnsv. Otherwise, rejectsv and goes to step 3.

For efficiency, a "cheap" method is necessary for generating random numbers fromg, and the scalarc should be small. The expected number of iterations to produce a single random number isc.

The following function implements an acceptance-rejection method for generating random numbers from pdff givenf,g, the RNGgrnd forg, and the constantc:

function X = accrejrnd(f,g,grnd,c,m,n)    X = zeros(m,n);% Preallocate memoryfor i = 1:m*n        accept = false;while accept == false            u = rand();            v = grnd();if c*u <= f(v)/g(v)               X(i) = v;               accept = true;endendendend

For example, the functionf(x)=xe-x2/2 satisfies the conditions for a pdf on[0,) (nonnegative and integrates to 1). The exponential pdf with mean 1,f(x)=e-x, dominatesg forc greater than about 2.2. Thus, you can userand andexprnd to generate random numbers fromf:

f = @(x)x.*exp(-(x.^2)/2);g = @(x)exp(-x);grnd = @()exprnd(1);rng('default')% For reproducibilityX = accrejrnd(f,g,grnd,2.2,1e4,1);

The pdff is actually aRayleigh Distribution with shape parameter 1. This example compares the distribution of random numbers generated by the acceptance-rejection method with those generated byraylrnd:

Y = raylrnd(1,1e4,1); histogram(X)holdonhistogram(Y)legend('A-R RNG','Rayleigh RNG')

Figure contains an axes object. The axes object contains 2 objects of type histogram. These objects represent A-R RNG, Rayleigh RNG.

Theraylrnd function uses a transformation method, expressing a Rayleigh random variable in terms of a chi-square random variable, which you compute usingrandn.

Acceptance-rejection methods also work for discrete distributions. In this case, the goal is to generate random numbers from a distribution with probability massPp(X=i)=pi, assuming that you have a method for generating random numbers from a distribution with probability massPq(X=i)=qi. The RNG proceeds as follows:

  1. Chooses a densityPq.

  2. Finds a constantc such thatpi/qic for alli.

  3. Generates a uniform random numberu.

  4. Generates a random numberv fromPq.

  5. Ifcupv/qv, accepts and returnsv. Otherwise, rejectsv and goes to step 3.

See Also

Topics

MathWorksMathWorks

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select:.

You can also select a web site from the following list

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Americas

Europe

Asia Pacific

Contact your local office


[8]ページ先頭

©2009-2025 Movatter.jp