ParaMonte Fortran 2.0.0
Parallel Monte Carlo and Machine Learning Library
See the latest version documentation.
pm_distNorm::setNormRandBox Interface Reference

Return a scalar or array of arbitrary rank of random values from the univariate Normal distribution, using the Box-Muller algorithm. More...

Detailed Description

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,
  1. 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

use pm_kind, only: LK
logical(LK) :: failed
! Box-Muller: Trigonometric-method implementation.
call random_number(rand1)
call random_number(rand2)
call setNormRandBox(rand1, rand2)
! Box-Muller: Rejection-method implementation.
do
call random_number(rand1)
call random_number(rand2)
call setNormRandBox(rand1, rand2, failed)
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...
Definition: pm_kind.F90:268
integer, parameter LK
The default logical kind in the ParaMonte library: kind(.true.) in Fortran, kind(....
Definition: pm_kind.F90:541

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.
Remarks
The procedures under discussion are elemental.
See also
getNormRand
setNormRand
setNormRandBox
getNormLogPDF
getNormCDF
setNormRandBox


Example usage

1program example
2
3 use pm_kind, only: SK
4 use pm_kind, only: IK, RK ! all real kinds are supported.
8 use pm_io, only: display_type
9
10 implicit none
11
12 integer(IK), parameter :: NP = 1000_IK
13 real(RK), dimension(NP) :: rand
14
15 type(display_type) :: disp
16 disp = display_type(file = "main.out.F90")
17
18 !call setLinSpace(mean, x1 = -5._RK, x2 = +5._RK)
19 !call setLogSpace(std, logx1 = log(0.1_RK), logx2 = log(10._RK))
20
21 call disp%skip()
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("!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
27 call disp%skip()
28
29 call disp%skip()
30 call disp%show("!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
31 call disp%show("! Normal random number from a Standard Normal distribution.")
32 call disp%show("!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
33 call disp%skip()
34
35 call disp%skip()
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))")
39 call setNormRandBox(rand(1), rand(2))
40 call disp%show("rand(1:2)")
41 call disp%show( rand(1:2) )
42 call disp%skip()
43
44 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
45 ! Output an example rand array for visualization.
46 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
47
48 ! Box-Muller Basic (Trigonometric) method.
49
50 block
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) &
62 , rand2(i) &
63 , rand3(i) &
64 , i = 1,NP &
65 )
66 close(fileUnit)
67 end block
68
69 ! Box-Muller Polar (Rejection) method.
70
71 block
72 logical :: failed
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")
77 do i = 1, NP
78 do
79 call random_number(rand1(1:2))
80 call setNormRandBox(rand1(1), rand1(2), failed = failed)
81 if (.not. failed) exit
82 end do
83 rand1(1:2) = rand1(1:2) * 3 + 2
84 do
85 call random_number(rand2(1:2))
86 call setNormRandBox(rand2(1), rand2(2), failed = failed)
87 if (.not. failed) exit
88 end do
89 do
90 call random_number(rand3(1:2))
91 call setNormRandBox(rand3(1), rand3(2), failed = failed)
92 if (.not. failed) exit
93 end do
94 rand3(1:2) = rand3(1:2) - 5._RK
95 do j = 1, 2
96 write(fileUnit,"(3(g0,:,' '))") rand1(j), rand2(j), rand3(j)
97 end do
98 end do
99 close(fileUnit)
100 end block
101
102end program example
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.
Definition: pm_io.F90:11726
This is a generic method of the derived type display_type with pass attribute.
Definition: pm_io.F90:11508
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...
Definition: pm_io.F90:252
type(display_type) disp
This is a scalar module variable an object of type display_type for general display.
Definition: pm_io.F90:11393
integer, parameter RK
The default real kind in the ParaMonte library: real64 in Fortran, c_double in C-Fortran Interoperati...
Definition: pm_kind.F90:543
integer, parameter IK
The default integer kind in the ParaMonte library: int32 in Fortran, c_int32_t in C-Fortran Interoper...
Definition: pm_kind.F90:540
integer, parameter SK
The default character kind in the ParaMonte library: kind("a") in Fortran, c_char in C-Fortran Intero...
Definition: pm_kind.F90:539
Generate and return an object of type display_type.
Definition: pm_io.F90:10282

Example Unix compile command via Intel ifort compiler
1#!/usr/bin/env sh
2rm main.exe
3ifort -fpp -standard-semantics -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
4./main.exe

Example Windows Batch compile command via Intel ifort compiler
1del main.exe
2set PATH=..\..\..\lib;%PATH%
3ifort /fpp /standard-semantics /O3 /I:..\..\..\include main.F90 ..\..\..\lib\libparamonte*.lib /exe:main.exe
4main.exe

Example Unix / MinGW compile command via GNU gfortran compiler
1#!/usr/bin/env sh
2rm main.exe
3gfortran -cpp -ffree-line-length-none -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
4./main.exe

Example output
1
2!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4! Generate random numbers from the (Standard) Normal distribution.
5!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
7
8
9!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
10! Normal random number from a Standard Normal distribution.
11!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
12
13
14call random_number(rand(1:2))
15call setNormRandBox(rand(1), rand(2))
16rand(1:2)
17+0.40083248968932186E-1, +1.0786619952232133
18
19

Postprocessing of the example output
1#!/usr/bin/env python
2
3import matplotlib.pyplot as plt
4import pandas as pd
5import numpy as np
6import glob
7import sys
8
9linewidth = 2
10fontsize = 17
11
12marker ={ "CK" : "-"
13 , "IK" : "."
14 , "RK" : "-"
15 }
16xlab = { "CK" : "Normal Random Number ( real/imaginary components )"
17 , "IK" : "Normal Random Number ( integer-valued )"
18 , "RK" : "Normal Random Number ( real-valued )"
19 }
20legends = [ r"$\mu = -5.,~\sigma = 1.0$"
21 , r"$\mu = 0.0,~\sigma = 1.0$"
22 , r"$\mu = 2.0,~\sigma = 3.0$"
23 ]
24
25for kind in ["IK", "CK", "RK"]:
26
27 pattern = "*." + kind + ".txt"
28 fileList = glob.glob(pattern)
29 if len(fileList) == 1:
30
31 df = pd.read_csv(fileList[0], delimiter = " ", header = None)
32
33 fig = plt.figure(figsize = 1.25 * np.array([6.4, 4.8]), dpi = 200)
34 ax = plt.subplot()
35
36 if kind == "CK":
37 plt.hist( df.values[:,0:3]
38 , histtype = "stepfilled"
39 , alpha = 0.5
40 , bins = 75
41 )
42 else:
43 plt.hist( df.values[:,0:3]
44 , histtype = "stepfilled"
45 , alpha = 0.5
46 , bins = 75
47 )
48 ax.legend ( legends
49 , fontsize = fontsize
50 )
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)
56
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")
60
61 plt.savefig(fileList[0].replace(".txt",".png"))
62
63 elif len(fileList) > 1:
64
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.

1module internal
2 use pm_kind, only: RKG => RK
3 implicit none
4contains
5 impure subroutine setNormRandBox(rand1, rand2)
6 real(RKG) , intent(out) :: rand1, rand2
7 real(RKG) :: factor, rsq
8 do
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
15 end do
16 factor = sqrt(-2._RKG * log(rsq) / rsq)
17 rand1 = rand1 * factor
18 rand2 = rand2 * factor
19 end subroutine
20end module
21
22
23! Test the performance of `setNormRandBoxBasic()` vs. `setNormRandBoxPolar()`.
24program benchmark
25
26 use iso_fortran_env, only: error_unit
28 use pm_io, only: display_type
29 use pm_kind, only: SK, IK, LK, RK
30 use internal, only: RKG
31
32 implicit none
33
34 integer(IK) :: itime
35 integer(IK) :: ibench
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
41
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) &
45 !, bench_type(name = SK_"getNormRandBox", exec = getNormRandBox, overhead = setOverhead, minsec = 0._RK, miniter = miniter) &
46 ], sorted = .true._LK, repeat = 1_IK)
47
49 call disp%show(bench%name, tmsize = 1_IK, bmsize = 1_IK)
50 disp = display_type(file = "main.out")
51
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))])
55 end do
56
57 write(*,"(*(g0,:,' '))") dummy
58 write(*,"(*(g0,:,' '))")
59
60contains
61
62 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
63 ! procedure wrappers.
64 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
65
66 subroutine setOverhead()
67 call initialize()
68 call finalize()
69 end subroutine
70
71 subroutine initialize()
72 call random_number(rand1)
73 call random_number(rand2)
74 end subroutine
75
76 subroutine finalize()
77 dummy = dummy + rand1 + rand2
78 end subroutine
79
80 subroutine setNormRandBoxBasic()
82 call initialize()
83 call setNormRandBox(rand1, rand2)
84 call finalize()
85 end subroutine
86
87 subroutine setNormRandBoxPolar()
89 logical(LK) :: failed
90 call initialize()
91 do
92 call setNormRandBox(rand1, rand2, failed)
93 if (.not. failed) exit
94 call random_number(rand1)
95 call random_number(rand2)
96 end do
97 call finalize()
98 end subroutine
99
100 !subroutine getNormRandBox()
101 ! block
102 ! use pm_distNorm, only: getNormRandBox
103 ! rand1 = getNormRandBox(mean = 0._RKG)
104 ! rand2 = getNormRandBox(mean = 0._RKG)
105 ! call finalize()
106 ! end block
107 !end subroutine
108
109 subroutine setNormRandBoxPolarImpure()
110 use internal, only: setNormRandBox
111 call setNormRandBox(rand1, rand2)
112 call finalize()
113 end subroutine
114
115end program benchmark
This module contains abstract interfaces and types that facilitate benchmarking of different procedur...
Definition: pm_bench.F90:41
This is the class for creating object to perform multiple benchmarks and performance-profiling.
Definition: pm_bench.F90:735
This is the class for creating benchmark and performance-profiling objects.
Definition: pm_bench.F90:386

Example Unix compile command via Intel ifort compiler
1#!/usr/bin/env sh
2rm main.exe
3ifort -fpp -standard-semantics -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
4./main.exe

Example Windows Batch compile command via Intel ifort compiler
1del main.exe
2set PATH=..\..\..\lib;%PATH%
3ifort /fpp /standard-semantics /O3 /I:..\..\..\include main.F90 ..\..\..\lib\libparamonte*.lib /exe:main.exe
4main.exe

Example Unix / MinGW compile command via GNU gfortran compiler
1#!/usr/bin/env sh
2rm main.exe
3gfortran -cpp -ffree-line-length-none -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
4./main.exe

Postprocessing of the benchmark output
1#!/usr/bin/env python
2
3import matplotlib.pyplot as plt
4import pandas as pd
5import numpy as np
6
7import os
8dirname = os.path.basename(os.getcwd())
9
10fontsize = 14
11
12df = pd.read_csv("main.out", delimiter = ",")
13colnames = list(df.columns.values)
14
15
18
19ax = plt.figure(figsize = 1.25 * np.array([6.4,4.6]), dpi = 200)
20ax = plt.subplot()
21
22for colname in colnames[:]:
23 plt.hist( np.log10(df[colname].values)
24 , histtype = "step"
25 , linewidth = 2
26 , alpha = .5
27 , bins = 50
28 )
29
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)
35#ax.set_xscale("log")
36#ax.set_yscale("log")
37plt.minorticks_on()
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[:]
42 #, loc='center left'
43 #, bbox_to_anchor=(1, 0.5)
44 , fontsize = fontsize
45 )
46
47plt.tight_layout()
48plt.savefig("benchmark." + dirname + ".runtime.png")
49
50
53
54ax = plt.figure(figsize = 1.25 * np.array([6.4,4.6]), dpi = 200)
55ax = plt.subplot()
56
57for colname in colnames[1:]:
58 plt.hist( np.log10(df[colname].values / df[colnames[0]].values)
59 , histtype = "step"
60 , linewidth = 2
61 , alpha = .5
62 , bins = 50
63 )
64
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)
70#ax.set_xscale("log")
71#ax.set_yscale("log")
72plt.minorticks_on()
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:]
77 #, bbox_to_anchor = (1, 0.5)
78 #, loc = "center left"
79 , fontsize = fontsize
80 )
81
82plt.tight_layout()
83plt.savefig("benchmark." + dirname + ".runtime.ratio.png")

Visualization of the benchmark output

Benchmark moral
  1. 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.
  2. 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.

  1. 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.
  2. 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.

Author:
Amir Shahmoradi, Oct 16, 2009, 11:14 AM, Michigan

Definition at line 2866 of file pm_distNorm.F90.


The documentation for this interface was generated from the following file: