"random" — 擬似乱数を生成する
*****************************

**ソースコード:** Lib/random.py

======================================================================

このモジュールでは様々な分布をもつ擬似乱数生成器を実装しています。

For integers, uniform selection from a range. For sequences, uniform
selection of a random element, a function to generate a random
permutation of a list in-place, and a function for random sampling
without replacement.

実数用としては、一様分布、正規分布 (ガウス分布)、対数正規分布、負の指
数分布、ガンマおよびベータ分布を計算する関数があります。角度の分布を生
成するにはフォン・ミーゼス分布が利用できます。

ほとんど全てのモジュール関数は、基礎となる関数 "random()" に依存します
。この関数はランダムな浮動小数点数を半開区間 [0.0, 1.0) 内に一様に生成
します。Python は中心となる乱数生成器としてメルセンヌツイスタを使いま
す。これは 53 ビット精度の浮動小数点を生成し、周期は 2**19937-1 です。
本体は C で実装されていて、高速でスレッドセーフです。メルセンヌツイス
タは、現存する中で最も広範囲にテストされた乱数生成器のひとつです。しか
しながら、メルセンヌツイスタは完全に決定論的であるため、全ての目的に合
致しているわけではなく、暗号化の目的には全く向いていません。

The functions supplied by this module are actually bound methods of a
hidden instance of the "random.Random" class.  You can instantiate
your own instances of "Random" to get generators that don’t share
state.  This is especially useful for multi-threaded programs,
creating a different instance of "Random" for each thread, and using
the "jumpahead()" method to make it likely that the generated
sequences seen by each thread don’t overlap.

Class "Random" can also be subclassed if you want to use a different
basic generator of your own devising: in that case, override the
"random()", "seed()", "getstate()", "setstate()" and "jumpahead()"
methods.  Optionally, a new generator can supply a "getrandbits()"
method — this allows "randrange()" to produce selections over an
arbitrarily large range.

バージョン 2.4 で追加: the "getrandbits()" method.

As an example of subclassing, the "random" module provides the
"WichmannHill" class that implements an alternative generator in pure
Python.  The class provides a backward compatible way to reproduce
results from earlier versions of Python, which used the Wichmann-Hill
algorithm as the core generator.  Note that this Wichmann-Hill
generator can no longer be recommended: its period is too short by
contemporary standards, and the sequence generated is known to fail
some stringent randomness tests.  See the references below for a
recent variant that repairs these flaws.

バージョン 2.3 で変更: MersenneTwister replaced Wichmann-Hill as the
default generator.

"random" モジュールは "SystemRandom" クラスも提供していて、このクラス
は OS が提供している乱数発生源を利用して乱数を生成するシステム関数
"os.urandom()" を使うものです。

警告: The pseudo-random generators of this module should not be used
  for security purposes.  Use "os.urandom()" or "SystemRandom" if you
  require a cryptographically secure pseudo-random number generator.

Bookkeeping functions:

random.seed(a=None)

   Initialize internal state of the random number generator.

   "None" or no argument seeds from current time or from an operating
   system specific randomness source if available (see the
   "os.urandom()" function for details on availability).

   If *a* is not "None" or an "int" or a "long", then "hash(a)" is
   used instead.  Note that the hash values for some types are
   nondeterministic when "PYTHONHASHSEED" is enabled.

   バージョン 2.4 で変更: formerly, operating system resources were
   not used.

random.getstate()

   乱数生成器の現在の内部状態を記憶したオブジェクトを返します。このオ
   ブジェクトを "setstate()" に渡して内部状態を復元することができます
   。

   バージョン 2.1 で追加.

   バージョン 2.6 で変更: State values produced in Python 2.6 cannot
   be loaded into earlier versions.

random.setstate(state)

   *state* は予め "getstate()" を呼び出して得ておかなくてはなりません
   。 "setstate()" は "getstate()" が呼び出された時の乱数生成器の内部
   状態を復元します。

   バージョン 2.1 で追加.

random.jumpahead(n)

   Change the internal state to one different from and likely far away
   from the current state.  *n* is a non-negative integer which is
   used to scramble the current state vector.  This is most useful in
   multi-threaded programs, in conjunction with multiple instances of
   the "Random" class: "setstate()" or "seed()" can be used to force
   all instances into the same internal state, and then "jumpahead()"
   can be used to force the instances』 states far apart.

   バージョン 2.1 で追加.

   バージョン 2.3 で変更: Instead of jumping to a specific state, *n*
   steps ahead, "jumpahead(n)" jumps to another state likely to be
   separated by many steps.

random.getrandbits(k)

   Returns a python "long" int with *k* random bits. This method is
   supplied with the MersenneTwister generator and some other
   generators may also provide it as an optional part of the API. When
   available, "getrandbits()" enables "randrange()" to handle
   arbitrarily large ranges.

   バージョン 2.4 で追加.

Functions for integers:

random.randrange(stop)
random.randrange(start, stop[, step])

   "range(start, stop, step)" の要素からランダムに選ばれた要素を返しま
   す。この関数は "choice(range(start, stop, step))" と等価ですが、実
   際には range オブジェクトを生成しません。

   バージョン 1.5.2 で追加.

random.randint(a, b)

   Return a random integer *N* such that "a <= N <= b".

Functions for sequences:

random.choice(seq)

   空でないシーケンス *seq* からランダムに要素を返します。 *seq* が空
   のときは、 "IndexError" が送出されます。

random.shuffle(x[, random])

   Shuffle the sequence *x* in place. The optional argument *random*
   is a 0-argument function returning a random float in [0.0, 1.0); by
   default, this is the function "random()".

   Note that for even rather small "len(x)", the total number of
   permutations of *x* is larger than the period of most random number
   generators; this implies that most permutations of a long sequence
   can never be generated.

random.sample(population, k)

   Return a *k* length list of unique elements chosen from the
   population sequence. Used for random sampling without replacement.

   バージョン 2.3 で追加.

   母集団自体を変更せずに、母集団内の要素を含む新たなリストを返します
   。返されたリストは選択された順に並んでいるので、このリストの部分ス
   ライスもランダムなサンプルになります。これにより、くじの当選者 (サ
   ンプル) を1等賞と2等賞（の部分スライス）に分けることも可能です。

   母集団の要素は *ハッシュ可能* でなくても、ユニークでなくてもかまい
   ません。母集団が繰り返しを含む場合、出現するそれぞれがサンプルに選
   択されえます。

   To choose a sample from a range of integers, use an "xrange()"
   object as an argument.  This is especially fast and space efficient
   for sampling from a large population:  "sample(xrange(10000000),
   60)".

以下の関数は特定の実数値分布を生成します。関数の引数の名前は、一般的な
数学の慣例で使われている分布の公式の対応する変数から取られています; こ
れらの公式のほとんどはどんな統計学のテキストにも載っています。

random.random()

   次のランダムな浮動小数点数（範囲は [0.0, 1.0) ）を返します。

random.uniform(a, b)

   "a <= b" であれば "a <= N <= b" 、"b < a" であれば "b <= N <= a" で
   あるようなランダムな浮動小数点数 *N* を返します。

   端点の値 "b" が範囲に含まれるかどうかは、等式 "a + (b-a) *
   random()" における浮動小数点の丸めに依存します。

random.triangular(low, high, mode)

   "low <= N <= high" でありこれら境界値の間に指定された最頻値 *mode*
   を持つようなランダムな浮動小数点数 *N* を返します。境界 *low* と
   *high* のデフォルトは 0 と 1 です。最頻値 *mode* 引数のデフォルトは
   両境界値の中点になり、対称な分布を与えます。

   バージョン 2.6 で追加.

random.betavariate(alpha, beta)

   ベータ分布です。引数の満たすべき条件は "alpha > 0" および "beta >
   0" です。 0 から 1 の範囲の値を返します。

random.expovariate(lambd)

   指数分布です。*lambd* は平均にしたい値の逆数です。(この引数は 「
   lambda」 と呼ぶべきなのですが、Python の予約語なので使えません。)
   返す値の範囲は *lambd* が正なら 0 から正の無限大、*lambd* が負なら
   負の無限大から 0 です。

random.gammavariate(alpha, beta)

   ガンマ分布です (ガンマ関数 *ではありません* ！)。引数の満たすべき条
   件は "alpha > 0" および "beta > 0" です。

   確率分布関数は:

                x ** (alpha - 1) * math.exp(-x / beta)
      pdf(x) =  --------------------------------------
                  math.gamma(alpha) * beta ** alpha

random.gauss(mu, sigma)

   ガウス分布です。 *mu* は平均であり、 *sigma* は標準偏差です。この関
   数は後で定義する関数 "normalvariate()" より少しだけ高速です。

random.lognormvariate(mu, sigma)

   対数正規分布です。この分布を自然対数を用いた分布にした場合、平均
   *mu* で標準偏差 *sigma* の正規分布になります。 *mu* は任意の値を取
   ることができ、*sigma* はゼロより大きくなければなりません。

random.normalvariate(mu, sigma)

   正規分布です。 *mu* は平均で、 *sigma* は標準偏差です。

random.vonmisesvariate(mu, kappa)

   *mu* は平均の角度で、0 から 2**pi* までのラジアンで表されます。
   *kappa* は濃度パラメータで、ゼロ以上でなければなりません。*kappa*
   がゼロに等しい場合、この分布は範囲 0 から 2**pi* の一様でランダムな
   角度の分布に退化します。

random.paretovariate(alpha)

   パレート分布です。 *alpha* は形状パラメータです。

random.weibullvariate(alpha, beta)

   ワイブル分布です。 *alpha* は尺度パラメタで、 *beta* は形状パラメー
   タです。

Alternative Generators:

class random.WichmannHill([seed])

   Class that implements the Wichmann-Hill algorithm as the core
   generator. Has all of the same methods as "Random" plus the
   "whseed()" method described below.  Because this class is
   implemented in pure Python, it is not threadsafe and may require
   locks between calls.  The period of the generator is
   6,953,607,871,644 which is small enough to require care that two
   independent random sequences do not overlap.

random.whseed([x])

   This is obsolete, supplied for bit-level compatibility with
   versions of Python prior to 2.1. See "seed()" for details.
   "whseed()" does not guarantee that distinct integer arguments yield
   distinct internal states, and can yield no more than about 2**24
   distinct internal states in all.

class random.SystemRandom([seed])

   Class that uses the "os.urandom()" function for generating random
   numbers from sources provided by the operating system. Not
   available on all systems. Does not rely on software state and
   sequences are not reproducible. Accordingly, the "seed()" and
   "jumpahead()" methods have no effect and are ignored. The
   "getstate()" and "setstate()" methods raise "NotImplementedError"
   if called.

   バージョン 2.4 で追加.

Examples of basic usage:

   >>> random.random()        # Random float x, 0.0 <= x < 1.0
   0.37444887175646646
   >>> random.uniform(1, 10)  # Random float x, 1.0 <= x < 10.0
   1.1800146073117523
   >>> random.randint(1, 10)  # Integer from 1 to 10, endpoints included
   7
   >>> random.randrange(0, 101, 2)  # Even integer from 0 to 100
   26
   >>> random.choice('abcdefghij')  # Choose a random element
   'c'

   >>> items = [1, 2, 3, 4, 5, 6, 7]
   >>> random.shuffle(items)
   >>> items
   [7, 3, 2, 5, 6, 4, 1]

   >>> random.sample([1, 2, 3, 4, 5],  3)  # Choose 3 elements
   [4, 1, 5]

参考: M. Matsumoto and T. Nishimura, 「Mersenne Twister: A
  623-dimensionally equidistributed uniform pseudorandom number
  generator」, ACM Transactions on Modeling and Computer Simulation
  Vol. 8, No. 1, January pp.3–30 1998.

  Wichmann, B. A. & Hill, I. D., 「Algorithm AS 183: An efficient and
  portable pseudo-random number generator」, Applied Statistics 31
  (1982) 188-190.

  Complementary-Multiply-with-Carry recipe for a compatible
  alternative random number generator with a long period and
  comparatively simple update operations.
