LoginSignup
7
5

More than 5 years have passed since last update.

fortranでの擬似乱数生成

Last updated at Posted at 2014-12-01

C言語などでは乱数生成には生成するためのseedが必要になる.

fortranでも同様にシードが必要になるので,それも含めて擬似乱数生成の備忘録

使用するのはこの以下の2つ

random_number(harvest)
harvest !実数のスカラか配列
random_seed([size][put][get])
size !シードを格納するのに必要な配列サイズを取得.
put !シードを設定.
get !現在のシードを取得.

シードが配列であるのもよくわからないんですが,配列の長さも環境によってまちまちなようで,シードのサイズの取得から行わないといけないと.

シードを変えてみる例
integer :: seedsize
integer,allocatable :: seed(:)
real :: rnd

call random_seed(size=seedsize) !サイズ取得
allocate(seed(seedsize)) !配列確保
call random_seed(get=seed) !現在のシードを取得
seed(1) = 1234567890 !ここでは10桁程度の適当な値

call random_number(rnd) !rndに乱数をセット

こんな具合に乱数を生成することが出来ます.
seed(1)を変えるだけでも生成される乱数は変わる.ただ,値は大きく変えないと,乱数自体も大きく変化しないらしい.

ちなみに,時間と組み合わせると毎回異なった乱数を生成できる.

以下はさっきのを少しだけ変えただけのもの

system_clock(count,count_rate,count_max)を利用した例
integer :: seedsize
integer,allocatable :: seed(:)
real :: rnd
integer :: c !時間を入れる

call system_clock(count=c) !時間を取得
call random_seed(size=seedsize)
allocate(seed(seedsize))
call random_seed(get=seed)
seed = c !時間を全部に代入

call random_number(rnd) !rndに乱数をセット

seed(1)だけ変えて連続で実行しても値が変わらなかったので,全部変えて実行したらいろいろな値を吐いてくれました.

7
5
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
7
5