確率論の小話 (2)

先日書いたベイズ統計と古典統計の違いについてのシミュレーションプログラムを作成したので掲載します

確率論の小話

カードのクラスを定義

class Card
    attr_reader :suite
    attr_reader :rank

    def initialize(suite, rank)
        @suite = suite
        @rank = rank
    end

    def is_dia?
        @suite == 'dia'
    end
end

52枚のカードの集合(デッキ)を定義

class Deck
    def initialize
        @deck = []
    end

    def add(card)
        @deck << card
    end

    def shuffle!
        @deck.shuffle!
    end

    def draw
        @deck.pop()
    end
end

ゲームの一連の流れをクラスに定義

class Game
    @@suites = ['spade', 'heart', 'dia', 'club']
    @@ranks = [1..13]

    attr_accessor :card_in_box

    def initialize
        @deck = Deck.new
        @@suites.each do |s|
            @@ranks.each do |r|
                card = Card.new(s, r)
                @deck.add(card)
            end
        end

        @deck.shuffle!
        @card_in_box = @deck.draw
    end

    def draw_three_cards
        3.times.map{|n| @deck.draw}
    end
end

シミュレーションの実行

# 箱にダイヤが含まれる単純な確率
games = 1000
count = 0
games.times do |g|
    game = Game.new
    card_in_box = game.card_in_box
    if card_in_box.is_dia?
        count += 1
    end
end

printf("Frequency principle : \t%.4f", count.quo(games))

rest_games = games
count = 0
while rest_games > 0 do
    game = Game.new
    three_cards = game.draw_three_cards
        
        # 引いた3枚のカードが全てダイヤの時
    if three_cards.all?{ |card| card.is_dia? } 
        limit -= 1
                # 箱に入っているカードもダイヤかどうか
        if box_in_card.is_dia?
            count += 1
        end
    end
end

printf("Bayes principle : \t%.4", count.quo(games))