2016年2月19日金曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Python 3.5 (プログラミング言語)

Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More! (Amit Saha (著)、No Starch Press)のChapter 5.(Playing with Sets and Probability)、Programming Challenges #2: Law of Large Numbers(No. 3607)を解いてみる。

#4: Law of Large Numbers(No. 3607)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import random


def rool_die():
    return random.randrange(1, 7)


def average(func, trials):
    total = 0
    for _ in range(trials):
        total += func()
    return total / trials

if __name__ == '__main__':
    print('Expected value: 3.5')
    TRIALS_LIST = [100, 100, 10000, 100000, 500000]
    for trials in TRIALS_LIST:
        print('Trials: {0} Trial average {1}'.format(
            trials, average(rool_die, trials)))

入出力結果(Terminal, IPython)

$ ./sample2.py
Expected value: 3.5
Trials: 100 Trial average 3.74
Trials: 100 Trial average 3.52
Trials: 10000 Trial average 3.5056
Trials: 100000 Trial average 3.50582
Trials: 500000 Trial average 3.497654
$

0 コメント:

コメントを投稿

Comments on Google+: