print('Hello world!')
import random
import matplotlib.pyplot as plt

# サイコロを n 回振って、その結果の分布を確認する
n = 10000  # 振る回数(10000回)
results = [random.randint(1, 6) for _ in range(n)]  # 各試行で1〜6のランダムな目を取得

# 平均(期待値)の計算
mean = sum(results) / n
print(f"{n}回の平均(期待値の近似): {mean:.2f}")  # 平均値を表示

# ヒストグラムの作成(サイコロの出目の分布を可視化)
plt.hist(
    results,
    bins=[1, 2, 3, 4, 5, 6, 7],  # 出目の範囲(1〜6)を設定
    align='left',  # バーを左寄せに配置
    rwidth=0.8,  # バーの幅を調整
    edgecolor='black'  # バーの縁を黒色で表示
)

# グラフのラベルを設定
plt.xlabel('Dice Roll Outcome')  # X軸(出た目)
plt.ylabel('Frequency')  # Y軸(回数)
plt.title('Dice Rolling Simulation')  # グラフのタイトル

# グラフを表示
plt.show()
##### 離散型確率変数の確率を考えてみる #####
# サイコロを1回投げて出た目の確率を考える
print("【離散型の説明】")
import numpy as np # NumPyモジュールのインポートする
import matplotlib.pyplot as plt # グラフを描くためのモジュール

values = np.arange(1, 7) # 確率変数は1,2,3,4,5,6の値を取る
print("valuesの中身:",values) # valuesの中身をプリント(確認)してみる

prob = np.ones(len(values)) / 6 # 確率計算
print("probの中身:",prob) # probの中身をプリント(確認)してみる

# サイコロの出る目の確率を描いてみる(縦棒グラフ)
plt.bar(values, prob)
plt.ylim(0, 1)
plt.title('Probability Distribution')
plt.xlabel('Dice')
plt.ylabel('$f(x)=P(X=x)$')
plt.show()

# このときの平均と分散を求めてみる
# 平均の計算
mean = np.sum(values * prob)
print(f'平均(期待値): {mean}')

# 分散の計算
variance = np.sum((values - mean) ** 2 * prob) # 「**」の演算子の意味:x**2はxの2乗の意味を表す
print(f'分散: {variance}')

# 標準偏差の計算
std = np.sqrt(variance)
print(f'標準偏差: {std}')


print("\n【連続型の説明】")
##### 連続型確率変数の確率を考えてみる#####
from scipy.integrate import quad

# 確率密度関数(-1<=x<=1でf(x) = 0.5,その他のときf(x)=0の場合)
def f(x):
    if -1 <= x <= 1:
        return 0.5
    else:
        return 0

# 積分範囲(無限大は np.inf を使う)
lower_limit = 0 # 左端
upper_limit = 2 # 右端

# quad関数を使用して積分
result,err = quad(f, lower_limit, upper_limit)

# 関数のグラフを描く
x_values = np.linspace(-1, 1, 1000)
y_values = [f(x) for x in x_values]

plt.figure(figsize=(8, 4)) # グラフサイズの調整

# 確率密度関数のグラフ
plt.plot(x_values, y_values, label=f'f(x) = {1/2}', color='blue')

# 積分範囲のグラフ
plt.fill_between(x_values, y_values, where=[(lower_limit <= x <= upper_limit) for x in x_values], color='blue', alpha=0.3, label='sekibunhaii')

plt.title('f(x)')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.xlim(-2,2)
plt.ylim(0,1)
plt.legend()
plt.show()

# 積分結果の表示
print(f'-1<=x<=1のとき,f(x) = {1/2},\nその他のとき,f(x) = 0となる確率密度関数がある。\nこれを以下の範囲で積分すると\n')
print(f"{lower_limit}から{upper_limit}の範囲で積分:積分結果= {result}, 誤差={err:.3e}")

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: