LoginSignup
0

More than 1 year has passed since last update.

Perlを使って乱数の出方を調べてみた。

Last updated at Posted at 2020-12-29

とある本を読んでいて、乱数のアルゴリズムは果たしてどのような偏りがあるのかが気になったので、Perlでスクリプトを書いてみた。

#(C)Tsubasa Kato 2020/11/7
#Last Updated on 2020/12/29
#Random Number Generator 
$counter = 1;
@number = 0;
$limit = 10000;
#decide upper limit of how many random numbers generated:
while ($counter <= $limit){
    $random_number = int(rand(10));
    @number[$counter] = $random_number;
    print "$counter: $random_number\n";
    $counter = $counter+1;

    $both = $both.@number[$counter - 1];


}

#prints all numbers made randomly.
print $both;
print @number[$counter];
#code used from: https://stackoverflow.com/questions/12948136/digit-occurence-of-a-number-in-perl
my (%counts, $sum);

while ($both =~ m/(\d)/g) {

    $counts{$1}++;
    $sum++;
}

print "The count each digit appears are: \n";
print "'$_' - $counts{$_}\n" for sort keys %counts;
print "The sum of all the totals is $sum\n";

出力(途中略)(例)

... 
9996: 6
9997: 6
9998: 6
9999: 5
10000: 7
667970441779473693333652299825501575481805785072233480307589190253118939996004889972812135817276495384858466221061134885961147664807314795423520407167266255738789149849690 
...

頻度分析の出力(例):
このように、10000回ゼロから九まで頻度分析してみると偏りが出ている。

The count each digit appears are: 
'0' - 955
'1' - 1021
'2' - 1033
'3' - 995
'4' - 1031
'5' - 958
'6' - 963
'7' - 1098
'8' - 982
'9' - 964
The sum of all the totals is 10000

発展版としてC言語などで書き直してみるのも良いかもしれない。
引用コードのURL:https://stackoverflow.com/questions/12948136/digit-occurence-of-a-number-in-perl

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
What you can do with signing up
0