0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

乱数表を得る方法

Posted at

乱数表を得るスクリプト

最近、急に乱数表が欲しくなったので質の良い乱数を得る簡単な方法を探しました。

/dev/random で「真」の乱数を得られることは割と有名だと思いますが、パッと 10 進数乱数を作る方法を知らなかったので調べました。
/dev/randomから取得したデータはバイナリ形式で提供されるため、それを10進数に変換する必要があります。

以下はシェルスクリプトを使用してバイナリデータを10進数に変換する方法の例です。

dd if=/dev/random bs=1 count=2000 2>/dev/null | od -An -tu1 > ../random_number.txt

od はバイナリデータを 10 進数に変換するコマンドです。
-Anオプションは、アドレス情報を表示しないように指定し、
-tu1オプションは、10進数形式で1バイトごとに表示することを指定します。

ddはデータのコピーと変換を行うコマンドです。
-bsはブロックサイズを表しておりサンプルでは 1 バイトです。
-countは個数を表しています。

以下は Python で同じことをするスクリプトです。
各言語の機能を使って乱数を得る方法については各言語のドキュメントにあたってください。/dev/urandomから乱数を得ている場合も多いので注意してください。

random_10_bytes.py
import os

def generate_random_decimal(num_bytes):
    with open('/dev/random', 'rb') as f:
        random_bytes = f.read(num_bytes)

    # バイナリデータを10進数に変換
    random_decimal = int.from_bytes(random_bytes, byteorder='big')

    return random_decimal

# 例: 10バイトのランダムデータを10進数に変換
random_data = generate_random_decimal(10)
print(random_data)

以上のスクリプトは質の良い乱数を得ることができますが、OS が溜め込んだエントロピープール以上の量の乱数は作れません。大量の乱数を必要とする場合は事前にコツコツ作っておくか、質の劣ることを理解した上でパスを/dev/urandomに書き換えてください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?