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?

ランダムは本当にランダムなのか、タイムスタンプ使っちゃダメか

0
Posted at

背景

プログラミング世界で本当なランダムはもちろん存在しなくて、あくまで模擬だけど、ある程度(要件による)本当のランダムに近づけば問題ないです。

ただし、そのランダムは本当のランダムが疑ったことがあるのでしょうか。そのランダム関数を使うより、タイムスタンプの方がより推測できないではないでしょうか。その疑問を多少持っているかもしれないので、軽く検証してみました。

ランダム VS ランダム

検証環境はGoogleのColabです。それぞれ100回と10,000回の1-10を生成して、その分布を比較します。

ランダム関数側の選手はPythonのランダムです。

random_values = [random.randint(1, 10) for _ in range(N)]

タイムスタンプ側は、もちろん秒とかを使うではなくて、ミリ秒とナノ秒を使います。

ミリ秒の場合

timestamp_values = []
for _ in range(N):
    ms_timestamp = int(time.time() * 1000)
    last_digit = ms_timestamp % 10
    timestamp_values.append(last_digit + 1)

ナノ秒の場合

nanosecond_values = []
for _ in range(10000):
    ns_timestamp = time.time_ns()
        last_digit = ns_timestamp % 10
        nanosecond_values.append(last_digit + 1)

結果

100回のPythonランダム関数 VS 100回のミリ秒

image.png

10,000回のPythonランダム関数 VS 10,000回のミリ秒

image.png

予想通り、Pythonと言っても実行時間が短いので、偏りが激しいです。


100回のPythonランダム関数 VS 100回のナノ秒

image.png

10,000回のPythonランダム関数 VS 10,000回のナノ秒

image.png

あまり差がないですね。

結論

実行環境・ユースケースにもよるけど、今回の実験結果ではタイムスタンプでもかなり近い結果が生成できます。ランダム関数のアルゴリズムを信じない人なら、タイムスタンプを使ってみましょうか

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?