Return a scalar or array of arbitrary rank of random values from the univariate Normal distribution, using the Box-Muller algorithm.
More...
Return a scalar or array of arbitrary rank of random values from the univariate Normal distribution, using the Box-Muller algorithm.
The procedures of this generic interface use the Box-Muller transform method to convert two uniformly distributed random input numbers to two output Normal-distributed random numbers.
The procedures deliberately return two output random values to ensure the purity of the procedures.
A more flexible implementation is available under the generic interface getNormRand.
- Parameters
-
[in,out] | rand1 | : The input/output scalar or array of the same shape as other array-like arguments, of,
-
type
real of kind any supported by the processor (e.g., RK, RK32, RK64, or RK128).
On input, it must contain a uniformly-distributed random number in the range \([0, 1)\).
On output, it contains a Normal-distributed random value.
|
[in,out] | rand2 | : The input/output scalar or array of the same shape as other array-like arguments, of the same type and kind as rand1 .
On input, it must contain a uniformly-distributed random number in the range \([0, 1)\).
On output, it contains a Normal-distributed random value.
|
[out] | failed | : The output scalar or array of the same shape as other array-like arguments, of type logical of default kind LK that is .true. if and only if the Box-Muller rejection method fails to generate two Normal-random values.
In such a case, the procedure should be called until failed = .false. is returned on output indicating success.
(optional. If missing, the trigonometric Normal random number generation method will be used which is slightly (by about \(\ms{25%}\)) slower but guaranteed to succeed.) |
Possible calling interfaces ⛓
logical(LK) :: failed
call random_number(rand1)
call random_number(rand2)
do
call random_number(rand1)
call random_number(rand2)
if (.not. failed) exit
end do
Return a scalar or array of arbitrary rank of random values from the univariate Normal distribution,...
This module contains classes and procedures for computing various statistical quantities related to t...
This module defines the relevant Fortran kind type-parameters frequently used in the ParaMonte librar...
integer, parameter LK
The default logical kind in the ParaMonte library: kind(.true.) in Fortran, kind(....
The condition 0. <= rand1 .and. rand1 < 1.
must hold for the corresponding input arguments.
The condition 0. <= rand2 .and. rand2 < 1.
must hold for the corresponding input arguments.
These conditions are verified only if the library is built with the preprocessor macro CHECK_ENABLED=1
.
- Warning
- The
pure
procedure(s) documented herein become impure
when the ParaMonte library is compiled with preprocessor macro CHECK_ENABLED=1
.
By default, these procedures are pure
in release
build and impure
in debug
and testing
builds.
- See also
- getNormRand
setNormRand
setNormRandBox
getNormLogPDF
getNormCDF
setNormRandBox
Example usage ⛓
12 integer(IK),
parameter :: NP
= 1000_IK
13 real(RK), dimension(NP) :: rand
15 type(display_type) :: disp
22 call disp%show(
"!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
23 call disp%show(
"!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
24 call disp%show(
"! Generate random numbers from the (Standard) Normal distribution.")
25 call disp%show(
"!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
26 call disp%show(
"!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
30 call disp%show(
"!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
31 call disp%show(
"! Normal random number from a Standard Normal distribution.")
32 call disp%show(
"!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
36 call disp%show(
"call random_number(rand(1:2))")
37 call random_number(rand(
1:
2))
38 call disp%show(
"call setNormRandBox(rand(1), rand(2))")
51 integer(IK) :: fileUnit, i
52 integer(IK),
parameter :: NP
= 5000_IK
53 real(RK), dimension(NP) :: rand1, rand2, rand3
54 call random_number(rand1)
55 call random_number(rand2)
56 call random_number(rand3)
57 call setNormRandBox(rand1(
1::
2), rand1(
2::
2)); rand1
= rand1
* 3.0_RK + 2._RK
58 call setNormRandBox(rand2(
1::
2), rand2(
2::
2)); rand2
= rand2
* 1.0_RK + 0._RK
59 call setNormRandBox(rand3(
1::
2), rand3(
2::
2)); rand3
= rand3
* 1.0_RK - 5._RK
60 open(newunit
= fileUnit, file
= "setNormRandBox.RK.txt")
61 write(fileUnit,
"(3(g0,:,' '))") ( rand1(i)
&
73 integer(IK) :: fileUnit, i, j
74 integer(IK),
parameter :: NP
= 5000_IK
75 real(RK), dimension(
2) :: rand1, rand2, rand3
76 open(newunit
= fileUnit, file
= "setNormRandBox.RK.txt")
79 call random_number(rand1(
1:
2))
81 if (
.not. failed)
exit
83 rand1(
1:
2)
= rand1(
1:
2)
* 3 + 2
85 call random_number(rand2(
1:
2))
87 if (
.not. failed)
exit
90 call random_number(rand3(
1:
2))
92 if (
.not. failed)
exit
94 rand3(
1:
2)
= rand3(
1:
2)
- 5._RK
96 write(fileUnit,
"(3(g0,:,' '))") rand1(j), rand2(j), rand3(j)
Return the linSpace output argument with size(linSpace) elements of evenly-spaced values over the int...
Return the logSpace output argument with size(logSpace) elements of logarithmically-evenly-spaced val...
This is a generic method of the derived type display_type with pass attribute.
This is a generic method of the derived type display_type with pass attribute.
This module contains procedures and generic interfaces for generating arrays with linear or logarithm...
This module contains classes and procedures for input/output (IO) or generic display operations on st...
type(display_type) disp
This is a scalar module variable an object of type display_type for general display.
integer, parameter RK
The default real kind in the ParaMonte library: real64 in Fortran, c_double in C-Fortran Interoperati...
integer, parameter IK
The default integer kind in the ParaMonte library: int32 in Fortran, c_int32_t in C-Fortran Interoper...
integer, parameter SK
The default character kind in the ParaMonte library: kind("a") in Fortran, c_char in C-Fortran Intero...
Generate and return an object of type display_type.
Example Unix compile command via Intel ifort
compiler ⛓
3ifort -fpp -standard-semantics -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
Example Windows Batch compile command via Intel ifort
compiler ⛓
2set PATH=..\..\..\lib;%PATH%
3ifort /fpp /standard-semantics /O3 /I:..\..\..\include main.F90 ..\..\..\lib\libparamonte*.lib /exe:main.exe
Example Unix / MinGW compile command via GNU gfortran
compiler ⛓
3gfortran -cpp -ffree-line-length-none -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
Example output ⛓
14call random_number(rand(
1:
2))
17+0.11555356399139420,
-1.3853275151713249
Postprocessing of the example output ⛓
3import matplotlib.pyplot
as plt
16xlab = {
"CK" :
"Normal Random Number ( real/imaginary components )"
17 ,
"IK" :
"Normal Random Number ( integer-valued )"
18 ,
"RK" :
"Normal Random Number ( real-valued )"
20legends = [
r"$\mu = -5.,~\sigma = 1.0$"
21 ,
r"$\mu = 0.0,~\sigma = 1.0$"
22 ,
r"$\mu = 2.0,~\sigma = 3.0$"
25for kind
in [
"IK",
"CK",
"RK"]:
27 pattern =
"*." + kind +
".txt"
28 fileList = glob.glob(pattern)
29 if len(fileList) == 1:
31 df = pd.read_csv(fileList[0], delimiter =
" ", header =
None)
33 fig = plt.figure(figsize = 1.25 * np.array([6.4, 4.8]), dpi = 200)
37 plt.hist( df.values[:,0:3]
38 , histtype =
"stepfilled"
43 plt.hist( df.values[:,0:3]
44 , histtype =
"stepfilled"
51 plt.xticks(fontsize = fontsize - 2)
52 plt.yticks(fontsize = fontsize - 2)
53 ax.set_xlabel(xlab[kind], fontsize = 17)
54 ax.set_ylabel(
"Count", fontsize = 17)
55 ax.set_title(
"Histograms of {} Normal random numbers".format(len(df.values[:, 0])), fontsize = 17)
57 plt.grid(visible =
True, which =
"both", axis =
"both", color =
"0.85", linestyle =
"-")
58 ax.tick_params(axis =
"y", which =
"minor")
59 ax.tick_params(axis =
"x", which =
"minor")
61 plt.savefig(fileList[0].replace(
".txt",
".png"))
63 elif len(fileList) > 1:
65 sys.exit(
"Ambiguous file list exists.")
Visualization of the example output ⛓
- Benchmarks:
Benchmark :: The runtime performance of setNormRandBox for different implementations of the Box-Muller algorithm. ⛓
6 real(RKG) ,
intent(out) :: rand1, rand2
7 real(RKG) :: factor, rsq
9 call random_number(rand1)
10 call random_number(rand2)
11 rand1
= 2._RKG * rand1
- 1._RKG
12 rand2
= 2._RKG * rand2
- 1._RKG
13 rsq
= rand1
**2 + rand2
**2
14 if (
0._RKG < rsq
.and. rsq
< 1._RKG)
exit
16 factor
= sqrt(
-2._RKG * log(rsq)
/ rsq)
17 rand1
= rand1
* factor
18 rand2
= rand2
* factor
26 use iso_fortran_env,
only:
error_unit
30 use internal,
only: RKG
36 real(RKG) :: rand1
= 0._RKG, rand2
= 0._RKG
37 real(RKG) :: dummy
= 0._RKG
38 type(benchMulti_type) :: bench
39 type(display_type) :: disp
40 integer(IK) :: miniter
= 10000_IK
42 bench
= benchMulti_type([
bench_type(name
= SK_
"setNormRandBoxBasic", exec
= setNormRandBoxBasic, overhead
= setOverhead, minsec
= 0._RK, miniter
= miniter)
&
43 ,
bench_type(name
= SK_
"setNormRandBoxPolar", exec
= setNormRandBoxPolar, overhead
= setOverhead, minsec
= 0._RK, miniter
= miniter)
&
44 ,
bench_type(name
= SK_
"setNormRandBoxPolarImpure", exec
= setNormRandBoxPolarImpure, overhead
= setOverhead, minsec
= 0._RK, miniter
= miniter)
&
46 ], sorted
= .true._LK, repeat
= 1_IK)
49 call disp%show(bench
%name, tmsize
= 1_IK, bmsize
= 1_IK)
52 write(
disp%unit,
"(*(g0,:,','))") (bench
%case(ibench)
%name, ibench
= 1,
size(bench
%case))
53 do itime
= 1,
size(bench
%case(
1)
%timing
%values)
54 call disp%show([(bench
%case(ibench)
%timing
%values(itime), ibench
= 1,
size(bench
%case))])
57 write(
*,
"(*(g0,:,' '))") dummy
58 write(
*,
"(*(g0,:,' '))")
66 subroutine setOverhead()
71 subroutine initialize()
72 call random_number(rand1)
73 call random_number(rand2)
77 dummy
= dummy
+ rand1
+ rand2
80 subroutine setNormRandBoxBasic()
87 subroutine setNormRandBoxPolar()
93 if (
.not. failed)
exit
94 call random_number(rand1)
95 call random_number(rand2)
109 subroutine setNormRandBoxPolarImpure()
110 use internal,
only: setNormRandBox
111 call setNormRandBox(rand1, rand2)
This module contains abstract interfaces and types that facilitate benchmarking of different procedur...
This is the class for creating object to perform multiple benchmarks and performance-profiling.
This is the class for creating benchmark and performance-profiling objects.
Example Unix compile command via Intel ifort
compiler ⛓
3ifort -fpp -standard-semantics -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
Example Windows Batch compile command via Intel ifort
compiler ⛓
2set PATH=..\..\..\lib;%PATH%
3ifort /fpp /standard-semantics /O3 /I:..\..\..\include main.F90 ..\..\..\lib\libparamonte*.lib /exe:main.exe
Example Unix / MinGW compile command via GNU gfortran
compiler ⛓
3gfortran -cpp -ffree-line-length-none -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
Postprocessing of the benchmark output ⛓
3import matplotlib.pyplot
as plt
8dirname = os.path.basename(os.getcwd())
12df = pd.read_csv(
"main.out", delimiter =
",")
13colnames = list(df.columns.values)
19ax = plt.figure(figsize = 1.25 * np.array([6.4,4.6]), dpi = 200)
22for colname
in colnames[:]:
23 plt.hist( np.log10(df[colname].values)
30plt.xticks(fontsize = fontsize)
31plt.yticks(fontsize = fontsize)
32ax.set_xlabel(
"Log10( Runtime [ seconds ] )", fontsize = fontsize)
33ax.set_ylabel(
"Count", fontsize = fontsize)
34ax.set_title(
" vs. ".join(colnames[:])+
"\nLower is better.", fontsize = fontsize)
38plt.grid(visible =
True, which =
"both", axis =
"both", color =
"0.85", linestyle =
"-")
39ax.tick_params(axis =
"y", which =
"minor")
40ax.tick_params(axis =
"x", which =
"minor")
41ax.legend ( colnames[:]
48plt.savefig(
"benchmark." + dirname +
".runtime.png")
54ax = plt.figure(figsize = 1.25 * np.array([6.4,4.6]), dpi = 200)
57for colname
in colnames[1:]:
58 plt.hist( np.log10(df[colname].values / df[colnames[0]].values)
65plt.xticks(fontsize = fontsize)
66plt.yticks(fontsize = fontsize)
67ax.set_xlabel(
"Log10( Runtime Ratio compared to {} )".format(colnames[0]), fontsize = fontsize)
68ax.set_ylabel(
"Count", fontsize = fontsize)
69ax.set_title(
"Runtime Ratio Comparison. Lower means faster.\nLower than 0 means faster than {}().".format(colnames[0]), fontsize = fontsize)
73plt.grid(visible =
True, which =
"both", axis =
"both", color =
"0.85", linestyle =
"-")
74ax.tick_params(axis =
"y", which =
"minor")
75ax.tick_params(axis =
"x", which =
"minor")
76ax.legend ( colnames[1:]
83plt.savefig(
"benchmark." + dirname +
".runtime.ratio.png")
Visualization of the benchmark output ⛓
Benchmark moral ⛓
- The benchmark procedures named
setNormRandBoxBasic
and setNormRandBoxPolar
call the generic interface setNormRandBox with the Basic and Polar (rejection sampling) implementations of the Box-Muller method, respectively.
While both implementations are pure subroutines, the third benchmark implementation is setNormRandBoxPolarImpure
is an impure
implementation of the Polar method that internally that does not require passing uniform random numbers to the subroutine.
- The benchmark results confirm the widespread community observation that the Polar implementation of the Box-Muller method (which uses rejection sampling) is slightly (by about 25%%) faster than the Basic implementation which involves two rather costly internal trigonometric function evaluations.
- Test:
- test_pm_distNorm
Final Remarks ⛓
If you believe this algorithm or its documentation can be improved, we appreciate your contribution and help to edit this page's documentation and source file on GitHub.
For details on the naming abbreviations, see this page.
For details on the naming conventions, see this page.
This software is distributed under the MIT license with additional terms outlined below.
-
If you use any parts or concepts from this library to any extent, please acknowledge the usage by citing the relevant publications of the ParaMonte library.
-
If you regenerate any parts/ideas from this library in a programming environment other than those currently supported by this ParaMonte library (i.e., other than C, C++, Fortran, MATLAB, Python, R), please also ask the end users to cite this original ParaMonte library.
This software is available to the public under a highly permissive license.
Help us justify its continued development and maintenance by acknowledging its benefit to society, distributing it, and contributing to it.
- Copyright
- Computational Data Science Lab
- Author:
- Amir Shahmoradi, Oct 16, 2009, 11:14 AM, Michigan
Definition at line 2866 of file pm_distNorm.F90.