跳至內容

GSL(GNU Scientific Library)參考手冊/隨機數發生器/生成隨機數

維基教科書,自由的教學讀本


生成隨機數

[編輯]

下面的函數返回整型或雙精度浮點型均勻分佈的隨機數。定義HAVE_INLINE時將使用這些函數的內聯(Inline)版本。要得到非均勻分佈,請見隨機數分佈

函數:

unsigned long int gsl_rng_get (const gsl_rng * r)

此函數從生成器r返回一個隨機整數。最大值和最小值取決於所使用的算法,但[min, max]之間的所有整數出現的機率是相等的。最大值max和最小值min可以通過輔助函數gsl_rng_max(r)和gsl_rng_min(r)來設置。

函數:

double gsl_rng_uniform (const gsl_rng * r)

此函數隨機返回一個[0,1)中的雙精度浮點數,範圍包括0.0,但不包括1.0。此函數的返回值通常是用gsl_rng_get(r)的返回值除以gsl_rng_max(r)+1.0得到的。 Some generators compute this ratio internally so that they can provide floating point numbers with more than 32 bits of randomness (the maximum number of bits that can be portably represented in a single unsigned long int).

函數:

double gsl_rng_uniform_pos (const gsl_rng * r)

此函數隨機返回一個[0,1)中的雙精度浮點數,範圍不包括0.0和1.0。該隨機數是採用gsl_rng_uniform的算法抽樣並捨去等於0的結果而得到的。此函數可用來避免0引起的奇異性。

函數:

unsigned long int gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n)
   This function returns a random integer from 0 to n-1 inclusive by scaling down and/or discarding samples from the generator r. All integers in the range [0,n-1] are produced with equal probability. For generators with a non-zero minimum value an offset is applied so that zero is returned with the correct probability.
   Note that this function is designed for sampling from ranges smaller than the range of the underlying generator. The parameter n must be less than or equal to the range of the generator r. If n is larger than the range of the generator then the function calls the error handler with an error code of GSL_EINVAL and returns zero.
   In particular, this function is not intended for generating the full range of unsigned integer values [0,2^32-1]. Instead choose a generator with the maximal integer range and zero minimum value, such as gsl_rng_ranlxd1, gsl_rng_mt19937 or gsl_rng_taus, and sample it directly using gsl_rng_get. The range of each generator can be found using the auxiliary functions described in the next section.