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

Return a scalar or array of arbitrary rank of random values from the standard univariate Normal distribution.
More...

Detailed Description

Return a scalar or array of arbitrary rank of random values from the standard univariate Normal distribution.

The procedures of this generic interface use the Ziggurat rejection method to generate Normal-distributed random numbers.

Parameters
[in,out]rng: The input/output scalar that can be an object of,
  1. type rngf_type, implying the use of intrinsic Fortran uniform RNG for Gamma RNG.
  2. type xoshiro256ssw_type, implying the use of xoshiro256** uniform RNG for Normal RNG.
(optional, default = rngf_type, implying the use of the intrinsic Fortran RNG.)
[out]rand: The output
  1. scalar, or
  2. array of rank 1, or
  3. array of arbitrary rank if the rng argument is missing or set to rngf_type, or
of,
  1. type real of kind any supported by the processor (e.g., RK, RK32, RK64, or RK128).
On output, it contains standard Normal-distributed random value(s).
[in]zig: The input matrix of shape (1:2, 0:*) of the same type and kind as the output argument rand, containing the information about the Ziggurat layers.
This matrix is directly (and must have been) returned by getZigNorm.
(optional. default = ZIG_RKB)


Possible calling interfaces

call setNormRand(rand(..))
call setNormRand(rand(..), zig(:,:))
call setNormRand(rand(:))
call setNormRand(rand(:), zig(:,:))
call setNormRand(rng, rand)
call setNormRand(rng, rand, zig(:,:))
call setNormRand(rng, rand(:))
call setNormRand(rng, rand(:), zig(:,:))
Return a scalar or array of arbitrary rank of random values from the standard univariate Normal distr...
This module contains classes and procedures for computing various statistical quantities related to t...
Warning
The condition precision(rand) <= ZIG_PRECISION must hold for the corresponding input arguments.
The condition all(0._RKG <= zig) must hold for the corresponding input arguments.
The condition size(zig, 1) == 2 must hold for the corresponding input arguments.
These conditions are verified only if the library is built with the preprocessor macro CHECK_ENABLED=1.
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. The procedures of this generic interface are always impure when the input argument rng is missing.
Remarks
The procedures under discussion are elemental. The procedures under this generic interface are non-elemental when the input argument zig is present or rng is set to an object of type xoshiro256ssw_type.
See also
getNormRand
setNormRand
setNormRandBox
getNormLogPDF
getNormCDF


Example usage

1program example
2
3 use pm_kind, only: SK
4 use pm_kind, only: IK, RK ! all real kinds are supported.
5 use pm_distNorm, only: setNormRand
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 ! mean, std,
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("! Normal random number from a Standard Normal distribution.")
24 call disp%show("!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
25 call disp%skip()
26
27 call disp%skip()
28 call disp%show("call setNormRand(rand(1))")
29 call setNormRand(rand(1))
30 call disp%show("rand(1)")
31 call disp%show( rand(1) )
32 call disp%skip()
33
34 call disp%skip()
35 call disp%show("call setNormRand(rand(1:5))")
36 call setNormRand(rand(1:5))
37 call disp%show("rand(1:5)")
38 call disp%show( rand(1:5) )
39 call disp%skip()
40
41 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
42 ! Output an example rand array for visualization.
43 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
44
45 block
46 use pm_distNorm, only: getZigNorm
47 real(RK) :: abserr
48 real(RK), allocatable :: zig(:,:)
49 integer(IK) :: fileUnit, i
50 integer(IK), parameter :: NP = 10000_IK
51 real(RK), dimension(NP) :: rand1, rand2, rand3
52 zig = getZigNorm(2_IK, abserr)
53 call setNormRand(rand1, zig); rand1 = rand1 * 3.0_RK + 2._RK
54 call setNormRand(rand2, zig); rand2 = rand2 * 1.0_RK + 0._RK
55 call setNormRand(rand3); rand3 = rand3 * 1.0_RK - 5._RK
56 open(newunit = fileUnit, file = "setNormRand.RK.txt")
57 write(fileUnit,"(3(g0,:,' '))") ( rand1(i) &
58 , rand2(i) &
59 , rand3(i) &
60 , i = 1,NP &
61 )
62 close(fileUnit)
63 end block
64
65end 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...
Generate and return the lower right edges of the rectangles of a Ziggurat partitioning of the Normal ...
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
This module defines the relevant Fortran kind type-parameters frequently used in the ParaMonte librar...
Definition: pm_kind.F90:268
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! Normal random number from a Standard Normal distribution.
4!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5
6
7call setNormRand(rand(1))
8rand(1)
9+0.46339148805818164
10
11
12call setNormRand(rand(1:5))
13rand(1:5)
14-0.51339321359071444, +1.8095264813581837, -0.46483668418807361, +0.68974876997698664, +0.88327355867959056
15
16

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 setNormRand for different implementations of the Box-Muller algorithm.

1! Test the overhead of calling `setNormRand()` vs. Fortran intrinsic procedure `random_number()`.
2program benchmark
3
4 use pm_kind, only: IK, RK, RKG => RK, SK
5 use pm_distNorm, only: xoshiro256ssw_type
6 use pm_distNorm, only: setNormRand
7 use pm_distNorm, only: getZigNorm
8 use pm_bench, only: bench_type
9
10 implicit none
11
12 integer(IK) :: ibench
13 integer(IK) :: nlay
14 integer(IK) :: iset
15 integer(IK) :: fileUnit
16 integer(IK) , parameter :: NSET = 13_IK
17 integer(IK) , parameter :: NSIM = 10000_IK
18 real(RKG) , allocatable :: zig(:,:)
19 real(RKG) :: rand(NSIM)
20 real(RKG) :: dummy = 0._RKG
21 type(bench_type) , allocatable :: bench(:)
22 type(xoshiro256ssw_type) :: rng
23
24 rng = xoshiro256ssw_type()
25 bench = [ bench_type(name = SK_"setNormRandX256", exec = setNormRandX256, overhead = setOverhead) &
26 , bench_type(name = SK_"setNormRandFRNG", exec = setNormRandFRNG, overhead = setOverhead) &
27 ]
28
29 open(newunit = fileUnit, file = "main.out", status = "replace")
30
31 write(fileUnit, "(*(g0,:,','))") "ZigguratLayerCount", (bench(ibench)%name, ibench = 1, size(bench))
32
33 loopOverZigSets: do iset = 1, NSET
34
35 nlay = 2**iset
36 zig = getZigNorm(nlay, dummy)
37 write(*,"(*(g0,:,' '))") "Benchmarking setNormRand() with ziggurat set size and abserr", nlay, dummy
38 do ibench = 1, size(bench)
39 bench(ibench)%timing = bench(ibench)%getTiming(miniter = 10_IK)
40 end do
41 write(fileUnit, "(*(g0,:,','))") nlay, (bench(ibench)%timing%mean / NSIM, ibench = 1, size(bench))
42 write(*,"(*(g0,:,' '))") dummy
43
44 end do loopOverZigSets
45
46 close(fileUnit)
47
48contains
49
50 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
51 ! procedure wrappers.
52 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
53
54 subroutine setOverhead()
55 call getDummy()
56 end subroutine
57
58 subroutine getDummy()
59 dummy = dummy + sum(rand)
60 end subroutine
61
62 subroutine setNormRandFRNG()
63 call setNormRand(rand, zig)
64 call getDummy()
65 end subroutine
66
67 subroutine setNormRandX256()
68 call setNormRand(rng, rand, zig)
69 call getDummy()
70 end subroutine
71
72end program benchmark
Generate and return an object of type timing_type containing the benchmark timing information and sta...
Definition: pm_bench.F90:574
This module contains abstract interfaces and types that facilitate benchmarking of different procedur...
Definition: pm_bench.F90:41
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[1:]:
23 plt.plot( df[colnames[0]].values
24 , df[colname].values
25 , linewidth = 2
26 )
27
28plt.xticks(fontsize = fontsize)
29plt.yticks(fontsize = fontsize)
30ax.set_xlabel(colnames[0], fontsize = fontsize)
31ax.set_ylabel("Runtime [ seconds ]", fontsize = fontsize)
32ax.set_title(" vs. ".join(colnames[1:])+"\nLower is better.", fontsize = fontsize)
33ax.set_xscale("log")
34ax.set_yscale("log")
35plt.minorticks_on()
36plt.grid(visible = True, which = "both", axis = "both", color = "0.85", linestyle = "-")
37ax.tick_params(axis = "y", which = "minor")
38ax.tick_params(axis = "x", which = "minor")
39ax.legend ( colnames[1:]
40 #, loc='center left'
41 #, bbox_to_anchor=(1, 0.5)
42 , fontsize = fontsize
43 )
44
45plt.tight_layout()
46plt.savefig("benchmark." + dirname + ".runtime.png")
47
48
51
52ax = plt.figure(figsize = 1.25 * np.array([6.4,4.6]), dpi = 200)
53ax = plt.subplot()
54
55for colname in colnames[1:]:
56 plt.plot( df[colnames[0]].values
57 , df[colname].values / df[colnames[1]].values.min()
58 , linewidth = 2
59 )
60
61plt.xticks(fontsize = fontsize)
62plt.yticks(fontsize = fontsize)
63ax.set_xlabel(colnames[0], fontsize = fontsize)
64ax.set_ylabel("Runtime compared to the fastest {}.".format(colnames[1]), fontsize = fontsize)
65ax.set_title("Runtime Ratio Comparison. Lower means faster.\nLower than 1 means faster than the fastest {}() run.".format(colnames[1]), fontsize = fontsize)
66ax.set_xscale("log")
67#ax.set_yscale("log")
68plt.minorticks_on()
69plt.grid(visible = True, which = "both", axis = "both", color = "0.85", linestyle = "-")
70ax.tick_params(axis = "y", which = "minor")
71ax.tick_params(axis = "x", which = "minor")
72ax.legend ( colnames[1:]
73 #, bbox_to_anchor = (1, 0.5)
74 #, loc = "center left"
75 , fontsize = fontsize
76 )
77
78plt.tight_layout()
79plt.savefig("benchmark." + dirname + ".runtime.ratio.png")

Visualization of the benchmark output

Benchmark moral
  1. The benchmark procedures named setNormRandX256 and setNormRandFRNG call the generic interface setNormRand to generate Normal random values via Ziggurat algorithm with the Xoshiro256** and the intrinsic Fortran Uniform RNG, respectively.
    This benchmark confirms the popular choice of the number of 256 Ziggurat layers as the optimal value.
    Nevertheless, the benchmarks appear to show improvements with even larger number of Ziggurat layers, depending on the platform, processor, and compiler choice.
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 2022 of file pm_distNorm.F90.


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