数学と統計
数値計算は基本的なプログラミングスキルです。Python の標準ライブラリは、基本的な数学関数から統計分析、正確な小数演算から分数演算まで、完全なツールセットを提供します。このレッスンでは、適切なシナリオに適切なモジュールを使う方法を学びます。
1. math — 数学関数
PYTHON
import math
# よく使われる定数
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
# 丸め
print(math.ceil(3.14)) # 4(天井)
print(math.floor(3.14)) # 3(床)
# 累乗と対数
print(math.pow(2, 10)) # 1024.0(2 の 10 乗)
print(math.sqrt(16)) # 4.0(平方根)
print(math.log(100, 10)) # 2.0(底 10 の対数)
# 三角関数
print(math.sin(math.pi / 2)) # 1.0
print(math.cos(0)) # 1.0
print(math.radians(180)) # 3.14159...(度からラジアン)
例:距離計算(難易度 ⭐)
PYTHON
import math
def distance(x1, y1, x2, y2):
"""2 点間の距離を計算"""
return math.sqrt((x2 - x1) 2 + (y2 - y1) 2)
def circle_area(radius):
"""円の面積を計算"""
return math.pi * radius ** 2
print(f"Distance: {distance(0, 0, 3, 4):.2f}") # 5.00
print(f"Circle area: {circle_area(5):.2f}") # 78.54
2. statistics — 統計分析
PYTHON
import statistics
data = [12, 15, 18, 20, 22, 25, 30, 35, 40]
# 中心傾向
print(statistics.mean(data)) # 24.11(平均)
print(statistics.median(data)) # 22(中央値)
# print(statistics.mode(data)) # 最頻値(一意の最頻値がないとエラー)
# ばらつき
print(statistics.stdev(data)) # 9.32(標本標準偏差)
print(statistics.variance(data)) # 86.86(標本分散)
例:スコア分析(難易度 ⭐⭐)
PYTHON
import statistics
scores = [85, 92, 78, 90, 88, 76, 95, 82, 89, 73]
print("=== Score Analysis ===")
print(f"Mean: {statistics.mean(scores):.1f}")
print(f"Median: {statistics.median(scores)}")
print(f"Max: {max(scores)}")
print(f"Min: {min(scores)}")
print(f"Std Dev: {statistics.stdev(scores):.2f}")
mean = statistics.mean(scores)
std = statistics.stdev(scores)
print("\n=== Grade Distribution ===")
for score in sorted(scores, reverse=True):
if score > mean + std:
level = "Excellent ⭐"
elif score > mean:
level = "Good 👍"
elif score > mean - std:
level = "Average"
else:
level = "Needs Work 💪"
print(f" {score:3d} — {level}")
3. decimal — 正確な小数演算
PYTHON
from decimal import Decimal, getcontext
# float の精度問題
print(0.1 + 0.2) # 0.30000000000000004 ❌
# Decimal の正確な計算
print(Decimal("0.1") + Decimal("0.2")) # 0.3 ✅
# 精度を設定
getcontext().prec = 4 # グローバル精度 4 桁
print(Decimal(1) / Decimal(3)) # 0.3333(4 桁)
# 金融計算は Decimal を使用
price = Decimal("19.99")
quantity = Decimal("3")
tax_rate = Decimal("0.08")
total = price * quantity
tax = total * tax_rate
print(f"Total: {total:.2f}") # 59.97
print(f"Tax: {tax:.2f}") # 4.80
print(f"Payable: {total + tax:.2f}") # 64.77
💡 金融計算には常に
Decimal を使用し、float は決して使わないでください。 0.1 + 0.2 の精度問題は金融では致命的です。Decimal は正確な小数演算のためにパフォーマンスを犠牲にします。
4. fractions — 分数演算
PYTHON
from fractions import Fraction
# 分数を作成
f1 = Fraction(1, 3) # 1/3
f2 = Fraction(2, 6) # 自動的に 1/3 に約分
print(f1) # 1/3
print(f2) # 1/3
print(f1 == f2) # True
# 分数演算
a = Fraction(1, 2)
b = Fraction(1, 3)
print(a + b) # 5/6
print(a * b) # 1/6
print(a / b) # 3/2
# 分数と浮動小数点数の変換
print(float(Fraction(1, 3))) # 0.3333333333
print(Fraction(0.25).limit_denominator()) # 1/4
よくあるユースケース
- math:幾何学(面積/体積)、三角関数、対数演算
- statistics:試験スコア分析、データレポート、科学実験データ
- decimal:E コマース価格計算、財務諸表、税計算
- fractions:レシピの比率、エンジニアリング比率、教育アプリケーション
❓ よくある質問
Q
math モジュールと組み込みの abs()、round()、sum() の違いは何ですか?A 組み込み関数は基本的な操作(絶対値、丸め、合計)を処理します。
math はより特殊な関数(三角関数、対数、階乗)を提供します。組み込み関数で十分な場合はそれを使用してください。Q
statistics.mean() は手動で平均を計算するよりも優れていますか?A
mean() は内部的に最適化されており(合計とカウントを 1 回のパスで)、大規模データセットでのパフォーマンスが良く、空のリストなどのエッジケースも処理します。Q
Fraction と Decimal はいつ使い分ければよいですか?A 正確な有理数演算が必要な場合(教育用ソフトウェアの分数練習など)は
Fraction を使用します。制御された精度での小数点計算(金融など)には Decimal を使用します。シンプルなケースでは float で十分です——日常のプログラミングの 99% ではどちらも必要ありません。📖 まとめ
math:ceil()/floor()丸め、sqrt()平方根、pi/e定数、三角関数statistics:mean()平均、median()中央値、stdev()標準偏差Decimal:正確な小数演算、金融に適する。Decimal("0.1")のように文字列から作成Fraction:正確な分数演算、自動約分
📝 練習問題
-
基本(難易度 ⭐):
mathモジュールを使って、半径 7 の円の面積と円周を計算してください。 -
中級(難易度 ⭐⭐):
data = [23, 45, 67, 12, 34, 56, 78, 90, 11, 43]として、statisticsで平均、中央値、標準偏差を計算。次にmathを使って「平均 ± 標準偏差」の範囲内にある値を判定してください。 -
上級(難易度 ⭐⭐⭐):「ショッピングカート会計」プログラムを書いてください。商品は名前、単価(
Decimal)、数量を持ちます。アイテム追加後、合計、消費税(8%)、割引(100 ごとに 10 引き)を計算し、最終金額を出力します。要件: すべての金額計算はDecimalを使用。



