다음 코드에서 시뮬레니션 숫자를 1에서 10000번 까지 올려서 반복해보면 50%에 근접한다는 사실을 알게 된다.
import random
num_simulations = 10000 # 10,000번 던지기
heads_count = 0 # 앞면 횟수
for _ in range(num_simulations):
# 0: 뒷면, 1: 앞면 (랜덤 선택)
result = random.randint(0, 1)
if result == 1:
heads_count += 1
probability = (heads_count / num_simulations) * 100
print(f"동전을 {num_simulations}번 던진 결과, 앞면 나올 확률은 약 {probability:.2f}% 입니다.")
주사위도 연구해 보세요.
import random
import matplotlib.pyplot as plt
simulation_counts = []
face_probabilities = [[] for _ in range(6)]
face_counts = [0] * 6
for i in range(1, 10001):
result = random.randint(1, 6)
face_counts[result - 1] += 1
simulation_counts.append(i)
for j in range(6):
prob = (face_counts[j] / i) * 100
face_probabilities[j].append(prob)
plt.figure(figsize=(10, 6))
for j in range(6):
plt.plot(simulation_counts, face_probabilities[j], label=f'{j+1}번 면 확률')
plt.axhline(y=100/6, color='r', linestyle='--', label='이론적 확률 16.67%')
plt.xlabel('시뮬레이션 횟수')
plt.ylabel('각 면의 확률 (%)')
plt.title('주사위 던지기 시뮬레이션: 확률 수렴 과정')
plt.legend()
plt.grid(True)
plt.show()