Numbers with a Gaussian distribution

From SklogWiki
Jump to: navigation, search
Source.png This page contains computer source code. If you intend to compile and use this code you must check for yourself the validity of the code. Please read the SklogWiki disclaimer.

Random number generators usually provide numbers having a uniform (flat) distribution. However, sometimes it is desirable to generate numbers with some other distributions. For example, the Gaussian (normal) distribution is of paramount importance.

Fortran 90 implementation[edit]

This Fortran 90 function is adapted from Ref. 1, based on an algorithm from the Numerical Recipes collection (Ref. 2). The function ran() calls a random number generator:

! Returns random numbers distributed following a Gaussian with
! unit variance

function gauss()

  implicit none

  real gauss

  real v1,v2,r

  real ranmar

  do
     v1=2.0*ranmar()-1.0
     v2=2.0*ranmar()-1.0
     r=v1*v1+v2*v2
     if(r.lt.1.0) exit
  enddo

  gauss=v1*sqrt(-2.0*log(r)/r)

  return

end function gauss

References[edit]

  1. Daan Frenkel and Berend Smit "Understanding Molecular Simulation: From Algorithms to Applications" p. 411 Academic Press (1996)
  2. Numerical Recipes (Third Edition) website