LoginSignup
1
1

More than 5 years have passed since last update.

GCI データサイエンティスト養成講座_第2回の問題

Posted at

GCI データサイエンティスト養成講座の第2回問題の回答例です。
第1回といい微妙にひねりのある問題なのが楽しいです。

第2回の問題

モンテカルロ法で円周率を求めよ。
モンテカルロ法というのは、パソコンの力を使ってランダムで大量に点をプロットし、そのうち幾つが条件をみたすか、というふうにごり押しをして割合を求める方法だと解釈しています。

import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
import math
import matplotlib.patches as patches

# (1)
np.random.seed(0)
random_last1 = np.random.uniform(0,1,10000)
random_last2 = np.random.uniform(0,1,10000)
random_last1
in_circle = {'x' : [], 'y' : []}
not_in_circle = {'x' : [], 'y' : []}

# (2)
for x,y in zip(random_last1, random_last2):
    norm =math.hypot(x,y)
    if norm > 1:
        not_in_circle['x'].append(x)
        not_in_circle['y'].append(y)
    else:
        in_circle['x'].append(x)
        in_circle['y'].append(y)

plt.plot(not_in_circle['x'], not_in_circle['y'], "o")
plt.plot(in_circle['x'], in_circle['y'], "o")

plt.grid(True)

len(in_circle['x']) /10000 * 4

1回1回が結構ヘビーだけど、だからこそこれをきちんとやれば基礎はきちんと身につくはず…!

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