Created
November 7, 2025 01:47
-
-
Save pgtwitter/42c30523f014f5d8263c4699a01a67de to your computer and use it in GitHub Desktop.
n回サイコロを振って目の総和を求め、その総和の十の位の桁の値(0-9)の分布をシミュレーションする(試行回数 3,500,000)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # %% | |
| import numpy as np | |
| from collections import Counter | |
| import matplotlib.pyplot as plt | |
| import matplotlib | |
| import matplotlib.font_manager as fm | |
| prop = fm.FontProperties(fname='/System/Library/Fonts/ヒラギノ角ゴシック W3.ttc') | |
| prop.set_weight = 'normal' | |
| matplotlib.rcParams['font.family'] = prop.get_name() | |
| matplotlib.rcParams['font.weight'] = 'normal' | |
| def simulate_dice_tens_digit_distribution(n, trials=100000): | |
| """ | |
| n回サイコロを振って目の総和を求め、その総和の十の位の桁の分布をシミュレーションする。 | |
| Parameters: | |
| n (int): サイコロを振る回数 | |
| trials (int): シミュレーションの試行回数(精度を上げるため) | |
| Returns: | |
| dict: 十の位の桁(0〜9以上)の出現頻度分布 | |
| """ | |
| # 各サイコロの目は1〜6の乱数を生成 | |
| sums = np.random.randint(1, 7, size=(trials, n)).sum(axis=1) | |
| # 総和の十の位の桁を抽出: //10 で十の位以下を取得、%10 で十の位の数字 | |
| tens_digits = (sums // 10) % 10 | |
| # 分布をカウント | |
| distribution = Counter(tens_digits) | |
| # 0〜9まできちんと辞書で返す(出現0でも含める) | |
| full_dist = {i: distribution.get(i, 0) / trials for i in range(10)} | |
| return full_dist | |
| def plot_distribution(dist, n): | |
| """ | |
| 分布を棒グラフで可視化 | |
| """ | |
| digits = list(dist.keys()) | |
| probs = list(dist.values()) | |
| plt.figure(figsize=(10, 6)) | |
| plt.bar(digits, probs, tick_label=digits, color='skyblue', edgecolor='black') | |
| plt.title(f'サイコロ{n}回の総和の十の位の桁の分布(モンテカルロ法 試行回数 {trials})') | |
| plt.xlabel('十の位の桁') | |
| plt.ylabel('出現確率') | |
| plt.ylim(0, max(probs) * 1.1) | |
| # 各バーの上に確率を表示 | |
| for i, p in enumerate(probs): | |
| plt.text(i, p + 0.001, f'{p:.4f}', ha='center', va='bottom') | |
| plt.grid(axis='y', alpha=0.3) | |
| plt.show() | |
| # === 実行例 === | |
| n = 1000 | |
| trials = 3500000 | |
| dist = simulate_dice_tens_digit_distribution(n, trials) | |
| print(f"サイコロを {n} 回振った場合の総和の十の位の桁の分布 (試行回数{trials}):") | |
| for digit, prob in sorted(dist.items()): | |
| print(f"桁 {digit}: {prob:.5f} ({prob*100:.3f}%)") | |
| # グラフ表示 | |
| plot_distribution(dist, n) |
Author
pgtwitter
commented
Nov 7, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment