中学社会669002 views
いろは3013586 views
雑学1473717 views
高校倫理1440914 views
MathPython498072 views
高校生物551985 views
高校物理160543 views
高校化学2925825 views
数学講師2890703 views
小学算数1201030 views
Help
Tools
NewsSpreadsheetCalendarBookkeepingMarkdown TablesLanguage Model NewsLinux CommandsSlidesTier ListPen ToolIllustrationCrayonWatercolorPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchSwirl EffectLine ArtOCR/HighlighterMakeup EditorFaviconVideo TrimmerScrolling VideoVideo TitleColor PickerColor ExtractorBonfireFireworksCherry BlossomWater RippleWater SplashBreaking GlassGlass TextureFabric TextureWood GrainMarble TextureBrick Wall TextureMetal TextureWashi Paper TextureCardboard TextureCSS ButtonIcon MakerBar ChartGrouped Bar ChartStacked Bar ChartPie ChartLine ChartArea ChartStacked Area ChartScatter Plot3D Bar Chart3D Pie ChartBar Chart RaceBubble ChartPopulation PyramidPictogramEarningsCandlestick ChartInvestment RiskMortgage SimulatorCalculatorMatrix CalculatorFunction GraphPolynomial ExpansionVenn DiagramField VisualizerRubik's Cube Group TheoryTraveling SalesmanVoronoi and DelaunayFractalUniversity Entrance Exam MathColumn ArithmeticDraw Math FiguresArithmetic AnimationArithmetic Word ProblemsCounting with Tree DiagramsCube NetsRolling DiceCross SectionsMotion PathMechanicsWavesUniversity Entrance Exam Physics解析力学Quantum MechanicsStatistical MechanicsRelativityCelestial MechanicsAstrophysicsCosmologyElectromagnetic WavesCapacitorsLight and LensesThermodynamicsHow Semiconductors WorkMolecular StructuresAtomic OrbitalsElectrochemical CellsChemical EquilibriumCrystal LatticesBuffer pHOrganic Reaction MapPeriodic TableComplex IonsDNA Double HelixCell DivisionMembrane ChannelsNerve ImpulseMuscle ContractionHormones and HomeostasisRock ClassificationWeatherConstellationsSolar and Lunar Eclipses3D ModelingFloor PlanSeismic StructuresIntersection TurnMaglevCooking AnimationOrigamiLive Viewer CountGeoJSON MapRailway MapPopulation MapCrime MapLand Price MapSchool MapShrine and Castle MapHouse of Representatives MapWord MapSolitaireReversiHakoiri MusumeChessHamburgerRippleSlide Puzzle MakerNeon PinballNovel MakerJapanese Typing PracticePiano Score EditorMusic TheoryShogi StrategyPiano Rhythm Game

English

Python で正規分布の確率計算とグラフ描画(SciPy)

SciPy の stats モジュールを使うと、正規分布の確率密度関数、累積分布関数、パーセント点などを簡単に計算できます。グラフ描画と合わせて使い方を確認しましょう。

必要なライブラリのインポート

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

正規分布オブジェクトの作成

stats.norm() で正規分布オブジェクトを作成します。

# 平均 50、標準偏差 10 の正規分布
mu, sigma = 50, 10
normal_dist = stats.norm(loc=mu, scale=sigma)

loc が平均、scale が標準偏差を表します。標準正規分布の場合は stats.norm() とするだけで が得られます。

確率密度関数(PDF)の計算

特定の値における確率密度を求めます。

# x = 60 での確率密度
x = 60
pdf_value = normal_dist.pdf(x)
print(f"x={x} での確率密度: {pdf_value:.6f}")

累積分布関数(CDF)の計算

を計算します。

# P(X <= 60)
prob = normal_dist.cdf(60)
print(f"P(X <= 60) = {prob:.4f}")

# P(X > 60) = 1 - P(X <= 60)
prob_upper = 1 - normal_dist.cdf(60)
print(f"P(X > 60) = {prob_upper:.4f}")

# P(40 <= X <= 60)
prob_between = normal_dist.cdf(60) - normal_dist.cdf(40)
print(f"P(40 <= X <= 60) = {prob_between:.4f}")

実行結果は P(X <= 60) = 0.8413P(X > 60) = 0.1587P(40 <= X <= 60) = 0.6827 となります。

パーセント点(逆関数)の計算

累積確率から対応する の値を求めます。

# 上位 5% の境界値
x_95 = normal_dist.ppf(0.95)
print(f"上位 5% の境界: {x_95:.2f}")

# 下位 2.5% と上位 2.5% の境界(95% 信頼区間の端点)
x_lower = normal_dist.ppf(0.025)
x_upper = normal_dist.ppf(0.975)
print(f"95% 区間: [{x_lower:.2f}, {x_upper:.2f}]")

正規分布のグラフを描く

確率密度関数のグラフを描きます。

x = np.linspace(20, 80, 200)
y = normal_dist.pdf(x)

plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2)
plt.fill_between(x, y, alpha=0.3)
plt.xlabel('x')
plt.ylabel('確率密度')
plt.title(f'正規分布 N({mu}, {sigma}²)')
plt.grid(True, alpha=0.3)
plt.show()

特定区間を塗りつぶす

の部分を強調表示します。

x = np.linspace(20, 80, 200)
y = normal_dist.pdf(x)

plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2)

# 40 <= x <= 60 の部分を塗りつぶし
x_fill = np.linspace(40, 60, 100)
y_fill = normal_dist.pdf(x_fill)
plt.fill_between(x_fill, y_fill, alpha=0.5, color='orange')

plt.xlabel('x')
plt.ylabel('確率密度')
plt.title(f'P(40 ≤ X ≤ 60) = {prob_between:.4f}')
plt.grid(True, alpha=0.3)
plt.show()

このようにして、確率計算の結果を視覚的に確認できます。