乱数を生成する

実数/浮動小数点
  • random: 0.0 ~ 1.0 の範囲で一様な乱数を生成する (0.0 以上 1.0 未満)
  • uniform: 指定した範囲で一様な乱数を生成する (a ~ b の範囲)
整数
  • randint: 指定した範囲から選択した整数を返す (a ~ b の範囲の整数/b を含む)
  • randrange: 指定した範囲、ステップの整数から選択した整数を返す
使用例
import random

rf = random.uniform(-2, 2)
ri = random.randint(1, 100)Code language: Python (python)

ドキュメント:

random | Python 3.x ドキュメント [公式]

uniform | Python 3.x ドキュメント [公式]

randint | Python 3.x ドキュメント [公式]

randrange | Python 3.x ドキュメント [公式]

参考:

random / randrange / randint – ランダムな小数/整数を生成するなど | note.nkmk.me

リストから選択する

  • choice: 要素を1つ選択する
  • choices: 複数回要素を選択する (要素は重複する)
  • shuffle: 要素をランダムに並べ替える (※破壊的変更)
  • sample: シーケンスを取得する (要素の重複なし)

ドキュメント:

choice | Python 3.x ドキュメント [公式]

choices | Python 3.x ドキュメント [公式]

shuffle | Python 3.x ドキュメント [公式]

sample | Python 3.x ドキュメント [公式]

参考:

choice / sample / choices – リストからランダムに要素を選択する | note.nkmk.me

shuffle / sample – リストの要素をシャッフル | note.nkmk.me

正規分布

  • gauss: 高速版 (※高速だがスレッドセーフではない)
  • normalvariate: スレッドセーフ版

ドキュメント:

random.gauss | Python 3.x ドキュメント [公式]

random.normalvariate | Python 3.x ドキュメント [公式]

シード

ドキュメント:

seed | Python 3.x ドキュメント [公式]

リファレンス

random – 疑似乱数を生成する | Python 3.x ドキュメント [公式]

記事をシェアする:
タグ:

コメントを残す

メールアドレスが公開されることはありません。 ※ が付いている欄は必須項目です

Protected by reCAPTCHA