Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
9
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Organization

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

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の値が入ります

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
9
Help us understand the problem. What are the problem?