본문 바로가기

Python/AI 수학 with Python

[Python] 확률의 개념

 

예제 1

[In]

# 확률로의 수렴
# 주사위를 던졌을 때, 5가 나오는 사건의 확률

# np.random.randint(n) : 0 ~ n-1 사이의 정수 반환

%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt

x = [] 
y = []

total = 0 # 시행 수
num_5 = 0 # 5가 나온 횟수
n = 5000 # 주사위를 던진 횟수

for i in range(n):
    if np.random.randint(6) + 1 == 5:
        num_5 += 1

    total += 1
    x.append(i)
    y.append(num_5 / total)
    
plt.plot(x, y)
plt.plot(x, [1/6] * n, linestyle = 'dashed') # 1/6이 n개 들어간 리스트

plt.xlabel('x', size = 14)
plt.ylabel('y', size = 14)
plt.grid()

plt.show()

[Out]

 

예제 2

[In]

# 확률로의 수렴
# 동전을 던졌을 때 위가 나오는 사건의 확률
%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt

x = []
y = []
total = 0 # 시행 수
num_front = 0 # 윗면이 나온 횟수
n = 5000 # 동전을 던진 횟수

for i in range(n):
    if np.random.randint(2) == 0: # 앞면 = 0, 뒷면 = 1
        num_front += 1
    total += 1
    x.append(i)
    y.append(num_front / total)

plt.plot(x, y)
plt.plot(x, [1/2] * n, linestyle = 'dashed') # 1/2가 n개 들어간 리스트
plt.ylim([0, 1])
plt.xlabel('x', size = 14)
plt.ylabel('y', size = 14)
plt.grid()

plt.show()

[Out]

 

두 개의 예제 모두 확률로 수렴해 나가는 것을 확인할 수 있다.