Sign in Join
Wiki copytemporary

Generating Random Numbers/pl: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Generating Random Numbers/pl

OldNewLine
1+<figure>
2+<img src="fpc_source_logo.png" title="fpc_source_logo.png" />
3+<figcaption>fpc_source_logo.png</figcaption>
4+</figure>
5+
6+**Liczby losowe** są ważnymi zasobami do zastosowań naukowych, edukacji, tworzenia gier i wizualizacji. Odgrywają kluczową rolę w symulacji numerycznej.
7+
8+Liczby losowe generowane przez algorytm to liczby pseudolosowe. Należą do (dużego) zbioru powtarzających się liczb, których kolejność jest niemożliwa lub przynajmniej trudna do przewidzenia. W przeciwieństwie do Delphi, który używa liniowego generatora kongruencjalnego (patrz [[Delphi compatible LCG Random|LCG Random kompatybilny z Delphi]]), Free Pascal używa algorytmu MersenneTwister dla swojej standardowej funkcji losowej [[doc:rtl/system/random.html|random]] zdefiniowanej w RTL. Przed pierwszym użyciem generator liczb losowych FPC musi zostać zainicjowany pojedynczym wywołaniem funkcji [[doc:rtl/system/randomize.html|randomize]], która ustawia ziarno generatora. Najlepiej jest to zrobić w fazie uruchamiania programu.
9+
10+Alternatywnie w systemach opartych na systemach Unix i Linux dostępne są urządzenia wirtualne [[Dev random|/dev/random]] i `/dev/urandom`. Generują liczby (pseudo) losowe na podstawie sprzętu.
11+
12+Trzecią możliwością jest użycie liczb losowych ze źródeł zewnętrznych, albo ze specjalistycznych urządzeń sprzętowych, albo ze źródeł publicznych, np. na podstawie danych dotyczących rozpadu promieniotwórczego.
13+
14+## Jednorodny rozkład
15+
16+Ciągły rozkład jednorodny (nazywany również rozkładem prostokątnym) reprezentuje rodzinę symetrycznych rozkładów prawdopodobieństwa. Tutaj dla każdego członka rodziny wszystkie przedziały tej samej długości na nośniku rozkładu są jednakowo prawdopodobne.
17+
18+Standardowa funkcja [[RTL]] [[doc:rtl/system/random.html|random]] generuje liczby losowe, które mają jednolity rozkład. Jeśli zostanie wywoływana bez parametru zwróci pseudolosową liczbę zmiennoprzecinkową w przedziale \[0, 1), tj. 0 \<= wynik \< 1. Jeśli random jest wywoływana z argumentem longint L, dostarcza losową liczbę zmiennoprzecinkową w przedziale \[0, L).
19+
20+Kolejny zestaw generatorów liczb losowych o równomiernym rozkładzie jest przedstawiony w [[Marsaglia&|generatorach liczb pseudolosowych Marsaglii]].
21+
22+Jednolicie rozmieszczone liczby losowe nie są przydatne w żadnej aplikacji. Do tworzenia liczb losowych z innych rozkładów potrzebne są specjalne algorytmy:
23+
24+## Normal (Gaussian) Distribution
25+
26+One of the more common algorithms to produce normally distributed random numbers from uniformly distributed random numbers is the [Box-Müller approach](http://en.wikipedia.org/wiki/Box–Muller_transform). The following function calculates Gaussian-distributed random numbers:
27+
28+``` pascal
29+ function rnorm (mean, sd: real): real;
30+ {Calculates Gaussian random numbers according to the Box-Müller approach}
31+ var
32+ u1, u2: real;
33+ begin
34+ u1 := random;
35+ u2 := random;
36+ rnorm := mean * abs(1 + sqrt(-2 * (ln(u1))) * cos(2 * pi * u2) * sd);
37+ end;
38+```
39+
40+The same algorithm is used by the [[doc:rtl/math/randg.html|randg]] randg function from the [[RTL]] [[doc:rtl/math/index.html|math]] unit:
41+
42+``` pascal
43+function randg(mean,stddev: float): float;
44+```
45+
46+## Exponential Distribution
47+
48+An exponential distribution occurs frequently in real-world problems. A classical example is the distribution of waiting times between independent Poisson-random events, e.g. the radioactive decay of nuclei \[Press et al. 1989\].
49+
50+The following function delivers a single real random number out of an exponential distribution. *Rate* is the inverse of the mean, and the constant *RESOLUTION* determines the granularity of generated random numbers.
51+
52+``` pascal
53+function randomExp(a, rate: real): real;
54+const
55+ RESOLUTION = 1000;
56+var
57+ unif: real;
58+begin
59+ if rate = 0 then
60+ randomExp := NaN
61+ else
62+ begin
63+ repeat
64+ unif := random(RESOLUTION) / RESOLUTION;
65+ until unif <> 0;
66+ randomExp := a - rate * ln(unif);
67+ end;
68+end;
69+```
70+
71+## Gamma Distribution
72+
73+The gamma distribution is a two-parameter family of continuous random distributions. It is a generalization of both the exponential distribution and the Erlang distribution. Possible applications of the gamma distribution include modelling and simulation of waiting lines, or queues, and actuarial science.
74+
75+The following function delivers a single real random number out of a gamma distribution. The shape of the distribution is defined by the parameters *a*, *b* and *c*. The function makes use of the function **randomExp** as defined above.
76+
77+``` pascal
78+function randomGamma(a, b, c: real): real;
79+const
80+ RESOLUTION = 1000;
81+ T = 4.5;
82+ D = 1 + ln(T);
83+var
84+ unif: real;
85+ A2, B2, C2, Q, p, y: real;
86+ p1, p2, v, w, z: real;
87+ found: boolean;
88+begin
89+ A2 := 1 / sqrt(2 * c - 1);
90+ B2 := c - ln(4);
91+ Q := c + 1 / A2;
92+ C2 := 1 + c / exp(1);
93+ found := False;
94+ if c < 1 then
95+ begin
96+ repeat
97+ repeat
98+ unif := random(RESOLUTION) / RESOLUTION;
99+ until unif > 0;
100+ p := C2 * unif;
101+ if p > 1 then
102+ begin
103+ repeat
104+ unif := random(RESOLUTION) / RESOLUTION;
105+ until unif > 0;
106+ y := -ln((C2 - p) / c);
107+ if unif <= power(y, c - 1) then
108+ begin
109+ randomGamma := a + b * y;
110+ found := True;
111+ end;
112+ end
113+ else
114+ begin
115+ y := power(p, 1 / c);
116+ if unif <= exp(-y) then
117+ begin
118+ randomGamma := a + b * y;
119+ found := True;
120+ end;
121+ end;
122+ until found;
123+ end
124+ else if c = 1 then
125+ { Gamma distribution becomes exponential distribution, if c = 1 }
126+ begin
127+ randomGamma := randomExp(a, b);
128+ end
129+ else
130+ begin
131+ repeat
132+ repeat
133+ p1 := random(RESOLUTION) / RESOLUTION;
134+ until p1 > 0;
135+ repeat
136+ p2 := random(RESOLUTION) / RESOLUTION;
137+ until p2 > 0;
138+ v := A2 * ln(p1 / (1 - p1));
139+ y := c * exp(v);
140+ z := p1 * p1 * p2;
141+ w := B2 + Q * v - y;
142+ if (w + D - T * z >= 0) or (w >= ln(z)) then
143+ begin
144+ randomGamma := a + b * y;
145+ found := True;
146+ end;
147+ until found;
148+ end;
149+end;
150+```
151+
152+## Erlang Distribution
153+
154+The Erlang distribution is a two parameter family of continuous probability distributions. It is a generalization of the exponential distribution and a special case of the gamma distribution, where *c* is an integer. The Erlang distribution has been first described by Agner Krarup Erlang in order to model the time interval between telephone calls. It is used for queuing theory and for simulating waiting lines.
155+
156+``` pascal
157+ function randomErlang(mean: real; k: integer): real;
158+ const
159+ RESOLUTION = 1000;
160+ var
161+ i: integer;
162+ unif, prod: real;
163+ begin
164+ if (mean <= 0) or (k < 1) then
165+ randomErlang := NaN
166+ else
167+ begin
168+ prod := 1;
169+ for i := 1 to k do
170+ begin
171+ repeat
172+ unif := random(RESOLUTION) / RESOLUTION;
173+ until unif <> 0;
174+ prod := prod * unif;
175+ end;
176+ randomErlang := -mean * ln(prod);
177+ end;
178+ end;
179+```
180+
181+## Poisson Distribution
182+
183+The Poisson distribution applies to integer values. It represents the probability of *k* successes, when the probability of a success in each trial is small and the rate of occurrence (the mean value) is constant.
184+
185+``` pascal
186+function randomPoisson(mean: integer): integer;
187+{ Generator for Poisson distribution (Donald Knuth's algorithm) }
188+const
189+ RESOLUTION = 1000;
190+var
191+ k: integer;
192+ b, l: real;
193+begin
194+ assert(mean > 0, 'mean < 1');
195+ k := 0;
196+ b := 1;
197+ l := exp(-mean);
198+ while b > l do
199+ begin
200+ k := k + 1;
201+ b := b * random(RESOLUTION) / RESOLUTION;
202+ end;
203+ randomPoisson := k - 1;
204+end;
205+```
206+
207+## t Distribution
208+
209+The t distribution (also referred to a Student's t distribution, since it was published by William Sealy Gosset in 1908 under the pseudonym *Student*) is a continuous probability distribution. Its shape is defined by one parameter, the degrees of freedom (*df*). In statistics, many estimators are t distributed. Therefore, Student's t-distribution plays a major role in a number of widely used statistical analyses, including Student's t-test for assessing the statistical significance of the difference between two sample means, the construction of confidence intervals for the difference between two population means, and in linear regression analysis. The t-distribution also arises in Bayesian analysis of data from a normal family.
210+
211+The following algorithm depends on the [[RTL]] function [[doc:rtl/system/random.html|random]] and on the **randomChisq** function
212+
213+``` pascal
214+function randomT(df: integer): real;
215+{ Generator for Student's t distribution }
216+begin
217+ if df < 1 then
218+ randomT := NaN
219+ else begin
220+ randomT := randg(0, 1) / sqrt(randomChisq(df) / df);
221+ end;
222+end;
223+```
224+
225+## Chi Squared Distribution
226+
227+The chi squared distribution is a continuous distribution of random numbers with *df* degrees of freedom. It is the distribution of a sum of the squares of *df* independent standard normal random variables. The chi squared distribution has numerous applications in inferential statistics, e.g. in estimating variances and for chi-squared tests. It is a special gamma distribution with *c* = *df*/ 2 and *b* = 2. Therefore the following function depends on the function **randomGamma**.
228+
229+``` pascal
230+function randomChisq(df: integer): real;
231+begin
232+ if df < 1 then
233+ randomChisq := NaN
234+ else
235+ randomChisq := randomGamma(0, 2, 0.5 * df);
236+end;
237+```
238+
239+## F Distribution
240+
241+The F distribution, also referred to as Fisher-Snedecor distribution, is a continuous probability distribution. It is used for F Test and ANOVA. It has two degrees of freedom that serve as shape parameters *v* and *w* and that are positive integers. The following function **randomF** makes use of **randomChisq**.
242+
243+``` pascal
244+function randomF(v, w: integer): real;
245+begin
246+ if (v < 1) or (w < 1) then
247+ randomF := NaN
248+ else
249+ randomF := randomChisq(v) / v / (randomChisq(w) / w);
250+end;
251+```
252+
253+## See also
254+
255+- [[Dev random]]
256+- [[Functions for descriptive statistics]]
257+- [[Marsaglia&|Marsaglia's pseudo random number generators]]
258+- [[A simple implementation of the Mersenne twister]]
259+- [[Delphi compatible LCG Random]]
260+- [[EverettRandom]]
261+
262+## References
263+
264+1. [G. E. P. Box and Mervin E. Muller, *A Note on the Generation of Random Normal Deviates*, The Annals of Mathematical Statistics (1958), Vol. 29, No. 2 pp. 610–611](http://projecteuclid.org/DPubS/Repository/1.0/Disseminate?view=body&id=pdf_1&handle=euclid.aoms/1177706645)
265+2. Dietrich, J. W. (2002). [Der Hypophysen-Schilddrüsen-Regelkreis](http://openlibrary.org/books/OL24586469M/Der_Hypophysen-Schilddrüsen-Regelkreis). Berlin, Germany: Logos-Verlag Berlin. ISBN 978-3-89722-850-4. OCLC 50451543.
266+3. Press, W. H., B. P. Flannery, S. A. Teukolsky, W. T. Vetterling (1989). [Numerical Recipes in Pascal](http://openlibrary.org/works/OL16807779W/). The Art of Scientific Computing, Cambridge University Press, ISBN 0-521-37516-9.
267+4. Richard Saucier, [Computer Generation of Statistical Distributions](http://ftp.arl.mil/random/random.pdf), ARL-TR-2168, US Army Research Laboratory, Aberdeen Proving Ground, MD, 21005-5068, March 2000.
268+5. R.U. Seydel, Generating Random Numbers with Specified Distributions. In: Tools for Computational Finance, Universitext, [DOI 10.1007/978-1-4471-2993-6_2](http://dx.doi.org/10.1007/978-1-4471-2993-6_2), © Springer-Verlag London Limited 2012
269+6. Christian Walck, Hand-book on STATISTICAL DISTRIBUTIONS for experimentalists, Internal Report SUF–PFY/96–01, University of Stockholm 2007
270+
271+\
272+
273+---
274+*From the Free Pascal wiki, page "Generating Random Numbers/pl", as it stood on 2020-11-08 after a change by Slawek, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history