🚀 Fortuna 乱数生成関数ドキュメント
Fortuna
は多言語対応の乱数生成ライブラリで、Python、C++、Go などの様々なプログラミング言語をサポートしています。豊富な確率分布関数と統計ツールを提供し、科学計算、データ分析、モンテカルロシミュレーションなどの分野で利用できます。
🚀 クイックスタート
Fortuna
は多言語に対応した乱数生成ライブラリで、様々な確率分布関数と統計ツールを提供します。以下に、Python での基本的な使い方を紹介します。
✨ 主な機能
- 多言語対応:複数の言語でのインターフェースを提供します。
- 豊富な確率分布:連続分布と離散分布の両方をサポートしています。
- 効率的なアルゴリズム:検証済みの乱数生成アルゴリズムを使用しています。
- モジュール化設計:拡張と統合が容易です。
📦 インストール
Python では、以下のコマンドを使用してインストールできます。
pip install fortuna
💻 使用例
基本的な使用法
一様分布
import Fortuna as fr
print(fr.uniform())
正規分布
import Fortuna as fr
print(fr.normal(0, 1))
コイントス
import Fortuna as fr
print(fr.coin(0.5))
高度な使用法
具体的な分布関数
離散分布
ベルヌーイ試行
- 説明:ベルヌーイ乱数を生成します。
- パラメータ:
p
(float) – 成功確率、デフォルトは 0.5。
- 例
print(fr.bernoulli(0.7))
二項分布
- 説明:二項分布の乱数を生成します。
- パラメータ:
n
(int) – 試行回数。
p
(float) – 1 回の試行での成功確率、デフォルトは 0.5。
- 例
print(fr.binomial(10, 0.3))
幾何分布
- 説明:成功するまでの失敗回数を表す幾何分布の乱数を生成します。
- パラメータ:
p
(float) – 成功確率、デフォルトは 0.5。
- 例
print(fr.geometric(0.4))
負の二項分布
- 説明:r 回の成功までの失敗回数を表す負の二項分布の乱数を生成します。
- パラメータ:
r
(int) – 成功回数。
p
(float) – 1 回の試行での成功確率、デフォルトは 0.5。
- 例
print(fr.negative_binomial(3, 0.7))
ポアソン分布
- 説明:単位時間内のイベント発生回数を表すポアソン分布の乱数を生成します。
- パラメータ:
lambda
(float) – 平均発生率、デフォルトは 1.0。
- 例
print(fr.poisson(2.5))
連続分布
一様分布
- 説明:区間 [low, high) の一様分布の乱数を生成します。
- パラメータ:
a
(float) – 区間の下限、デフォルトは 0.0。
b
(float) – 区間の上限、デフォルトは 1.0。
- 例
print(fr.uniform(0, 5))
正規分布
- 説明:正規分布(ガウス分布)の乱数を生成します。
- パラメータ:
mean
(float) – 分布の平均、デフォルトは 0.0。
std_dev
(float) – 分布の標準偏差、デフォルトは 1.0。
- 例
print(fr.normal(5, 2))
指数分布
- 説明:イベント間の待機時間をモデル化するための指数分布の乱数を生成します。
- パラメータ:
lambda
(float) – 平均発生率、デフォルトは 1.0。
- 例
print(fr.exponential(0.5))
パレート分布
- 説明:自然や社会現象の長尾分布をモデル化するためのパレート分布の乱数を生成します。
- パラメータ:
shape
(float) – 分布の形状パラメータ、デフォルトは 2.0。
- 例
print(fr.pareto(2.5))
ワイブル分布
- 説明:信頼性工学や風速分析で使用されるワイブル分布の乱数を生成します。
- パラメータ:
shape
(float) – 分布の形状パラメータ、デフォルトは 2.0。
scale
(float) – 分布の尺度パラメータ、デフォルトは 1.0。
- 例
print(fr.weibull(3, 2))
カイ二乗分布
- 説明:統計的推論で使用されるカイ二乗分布の乱数を生成します。
- パラメータ:
degrees_of_freedom
(int) – 自由度、デフォルトは 1。
- 例
print(fr.chi_squared(5))
F 分布
- 説明:分散分析で使用される F 分布の乱数を生成します。
- パラメータ:
numerator_dof
(int) – 分子の自由度。
denominator_dof
(int) – 分母の自由度。
- 例
print(fr.f_distribution(5, 10))
t 分布
- 説明:小サンプルの統計的推論で使用される t 分布の乱数を生成します。
- パラメータ:
degrees_of_freedom
(int) – 自由度、デフォルトは 1。
- 例
print(fr.t_distribution(3))
対数正規分布
- 説明:積や成長率をモデル化するための対数正規分布の乱数を生成します。
- パラメータ:
mu
(float) – 対数の平均、デフォルトは 0.0。
sigma
(float) – 対数の標準偏差、デフォルトは 1.0。
- 例
print(fr.log_normal(0, 0.5))
コーシー分布
- 説明:高尾分布であるコーシー分布の乱数を生成します。
- パラメータ:
location
(float) – 分布の位置、デフォルトは 0.0。
scale
(float) – 分布の尺度、デフォルトは 1.0。
- 例
print(fr.cauchy(0, 2))
ベータ分布
- 説明:確率密度関数をモデル化するためのベータ分布の乱数を生成します。
- パラメータ:
alpha
(float) – 第 1 形状パラメータ、デフォルトは 1.0。
beta
(float) – 第 2 形状パラメータ、デフォルトは 1.0。
- 例
print(fr.beta(2, 5))
統計ツール
ランダムサンプリング
非復元抽出
import numpy as np
population = np.array([10, 20, 30, 40, 50])
print(fr.sample(population, 3))
層化抽出
population = {'A': [1, 2, 3], 'B': [4, 5, 6]}
print(fr.stratified_sample(population, 2))
仮説検定
コルモゴロフ・スミルノフ検定
sample = [1.2, 1.5, 2.0, 2.5, 3.0]
print(fr.kolmogorov_smirnov_test(sample))
シャピロ・ウィルク検定
sample = [1.2, 1.5, 2.0, 2.5, 3.0]
print(fr.shapiro_wilk_test(sample))
統計モデリング
線形回帰
import pandas as pd
data = {'x': [1, 2, 3, 4, 5], 'y': [2, 3, 5, 6, 7]}
df = pd.DataFrame(data)
model = fr.linear_regression(df, 'x', 'y')
print(model.summary())
ロジスティック回帰
data = {'x': [1, 2, 3, 4, 5], 'y': [0, 0, 1, 1, 1]}
df = pd.DataFrame(data)
model = fr.logistic_regression(df, 'x', 'y')
print(model.summary())
具体的な例
モンテカルロシミュレーション
def roll_dice():
return np.random.randint(1, 7)
results = [roll_dice() for _ in range(10000)]
print(f"Mean: {np.mean(results)}, Variance: {np.var(results)}")
リスク管理
returns = np.random.normal(loc=0.05, scale=0.1, size=1000)
portfolio_value = 1000 * (1 + returns).cumprod()
print(f"Expected Return: {np.mean(returns)*100}%, Volatility: {np.std(returns)*100}%")
plt.plot(portfolio_value)
plt.show()
品質管理
sample_size = 50
defects = np.random.binomial(n=10, p=0.05, size=100)
control_limits = fr.control_limits(sample_size, defects)
print(f"Upper Control Limit: {control_limits[0]}, Lower Control Limit: {control_limits[1]}")
plt.plot(defects)
plt.axhline(y=control_limits[0], color='red')
plt.axhline(y=control_limits[1], color='red')
plt.show()
まとめ
乱数生成と統計シミュレーションは、科学研究、エンジニアリング設計、金融分析などの多くの分野で重要な役割を果たしています。NumPy や Fortuna
のようなライブラリを使用することで、効率的にデータサンプリングとモデリングを行い、意思決定に信頼性の高いサポートを提供することができます。
乱数を効果的に生成し、様々な統計シミュレーションを行うために、以下の手順を推奨します。
手順 1: 必要なライブラリをインストール
まず、NumPy と Fortuna
ライブラリをインストールしてください。これらのライブラリは、さまざまな分布の乱数を生成し、統計分析を行うための豊富な関数を提供します。
pip install numpy fortuna
手順 2: 必要なライブラリをインポート
Python スクリプトで NumPy と Fortuna
をインポートします。
import numpy as np
from fortuna import random, distributions
手順 3: 一様分布の乱数を生成
random.uniform
関数を使用して、区間 [0,1) の一様分布の乱数を生成します。
single_random = random.uniform()
print(f"Single Uniform Random Number: {single_random}")
array_random = random.uniform(size=5)
print("\nArray of Uniform Random Numbers:")
print(array_random)
手順 4: 正規分布の乱数を生成
random.normal
関数を使用して、平均 0、標準偏差 1 の正規分布の乱数を生成します。
single_normal = random.normal()
print(f"\nSingle Normal Random Number: {single_normal}")
array_normal = random.normal(size=5)
print("\nArray of Normal Random Numbers:")
print(array_normal)
手順 5: カスタム分布の乱数を生成
確率質量関数(PMF)または確率密度関数(PDF)を渡すことで、カスタム分布の乱数を生成できます。
pmf = np.array([1/6, 1/6, 1/6, 1/6, 1/6, 1/6])
custom_discrete = distributions.Categorical(pmf)
discrete_random = custom_discrete.sample(size=5)
print("\nCustom Discrete Random Numbers:")
print(discrete_random)
lambda_param = 0.5
pdf = lambda x: lambda_param * np.exp(-lambda_param * x)
custom_continuous = distributions.CustomDistribution(pdf)
continuous_random = custom_continuous.sample(size=5)
print("\nCustom Continuous Random Numbers:")
print(continuous_random)
手順 6: 統計シミュレーションを行う
生成した乱数を利用して、モンテカルロ積分、リスク分析、仮説検定などの様々な統計シミュレーションを行います。
def monte_carlo_pi(n_samples):
random_points = random.uniform(low=-1, high=1, size=(n_samples, 2))
inside_circle = (random_points[:, 0]**2 + random_points[:, 1]**2) <= 1
return np.mean(inside_circle) * 4
n_samples = 10000
pi_estimation = monte_carlo_pi(n_samples)
print(f"\nMonte Carlo Estimation of π with {n_samples} samples: {pi_estimation}")
手順 7: 結果を可視化
matplotlib を使用して、生成した乱数やシミュレーション結果を可視化します。
import matplotlib.pyplot as plt
plt.hist(array_normal, bins=15, density=True, alpha=0.6, color='b')
plt.title('Normal Distribution Sample')
plt.xlabel('Value')
plt.ylabel('Probability Density')
plt.show()
points = random.uniform(low=-1, high=1, size=(n_samples, 2))
inside = points[points[:, 0]**2 + points[:, 1]**2 <= 1]
outside = points[points[:, 0]**2 + points[:, 1]**2 > 1]
plt.scatter(inside[:, 0], inside[:, 1], color='blue', alpha=0.5)
plt.scatter(outside[:, 0], outside[:, 1], color='red', alpha=0.5)
plt.title('Monte Carlo Integration for π')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
手順 8: 結果を分析
生成した乱数とシミュレーション結果に基づいて、平均、分散、またはその他の必要な統計量を計算するなどの統計分析を行い、必要に応じてパラメータやアルゴリズムを調整します。
まとめ
上記の手順を通じて、NumPy と Fortuna
ライブラリを効果的に利用して、さまざまな分布の乱数を生成し、複雑な統計シミュレーションを行うことができます。これは、科学研究、エンジニアリング設計、金融モデリングなどの分野で非常に有用であり、データ駆動のより賢明な意思決定を支援します。