13
9

More than 5 years have passed since last update.

Haskellで簡単に乱数を使ってみる

Last updated at Posted at 2015-04-25

Haskellで乱数というとすぐにStdGenが出てきて面倒くさいイメージがありますが
再現性を気にせず手軽にランダムな値が欲しいだけなら難しいことを考える必要はありません

以下はモンテカルロ法で円周率を求めるプログラムです。
乱数生成に使っているのはSystem.RandomrandomRIOというRandomクラスのメソッドです

import System.Random

trial :: Int -> IO Int
trial inner = do
    x <- randomRIO (0, 1) :: IO Double
    y <- randomRIO (0, 1) :: IO Double
    if x ^ 2 + y ^ 2 <= 1
    then return (inner + 1)
    else return inner

experience :: [IO Int]
experience = iterate (>>= trial) (return 0) 

main = do
    inner <- experience !! 10000
    print $ 4 * (fromIntegral inner) / 10000

これでx, yには0から1までのランダムなDoulbeの値が入ります

13
9
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
13
9