高校物理で学ぶPython



```Python
# Program Name: thermodynamic_cycle.py  
# Creation Date: 20250609  
# Overview: Compute work, heat, and efficiency for a 4-step thermodynamic cycle (A→B→C→D→A)  
# Usage: Change pA, pB, VA, VC for different cycle conditions  

# ライブラリのインストール（必要な場合）  
# !pip install sympy matplotlib  

# --- ライブラリ読込 ---  
from sympy import symbols, Rational, simplify, lambdify  
import matplotlib.pyplot as plt  

# --- パラメータ定義（数値一元管理） ---  
pA_val = 1.0e5   # Pa：状態A・Dの圧力 [Pressure at A,D]  
pB_val = 2.0e5   # Pa：状態B・Cの圧力 [Pressure at B,C]  
VA_val = 0.001   # m³：状態A・Bの体積 [Volume at A,B]  
VC_val = 0.003   # m³：状態C・Dの体積 [Volume at C,D]  

# --- 記号定義 [Symbolic variable definition] ---  
pA, pB, VA, VC = symbols('pA pB VA VC', real=True, positive=True)  

# --- 熱量計算（吸熱Qin・放熱Qout）と効率式 [Heat and efficiency formula] ---  
Q_in = -pB * VA - Rational(3, 2) * pA * VA + Rational(5, 2) * pB * VC  
Q_out = Rational(3, 2) * pB * VC + pA * VC - Rational(5, 2) * pA * VA  
eta_expr = simplify(2 * (pB - pA) * (VC - VA) / (-pB * VA - 3 * pA * VA + 5 * pB * VC))  

# --- 数値関数に変換 [Convert symbolic to numeric functions] ---  
Qin_func = lambdify((pA, pB, VA, VC), Q_in)  
Qout_func = lambdify((pA, pB, VA, VC), Q_out)  
eta_func = lambdify((pA, pB, VA, VC), eta_expr)  

# --- 数値計算 [Evaluate numeric results] ---  
Qin = Qin_func(pA_val, pB_val, VA_val, VC_val)  
Qout = Qout_func(pA_val, pB_val, VA_val, VC_val)  
eta = eta_func(pA_val, pB_val, VA_val, VC_val)  

# --- 結果出力 [Print results with units] ---  
print(f"加えられる熱量 Q_in = {Qin:.2f} J")      # Absorbed heat  
print(f"放出される熱量 Q_out = {Qout:.2f} J")      # Released heat  
print(f"熱効率 Efficiency = {eta:.2%}")            # Efficiency  

# --- 状態点定義 [Define points for p-V plot] ---  
points = {
    "A": (VA_val, pA_val),
    "B": (VA_val, pB_val),
    "C": (VC_val, pB_val),
    "D": (VC_val, pA_val)
}

# --- p-Vダイアグラム作成 [Create p-V diagram] ---  
cycle = ["A", "B", "C", "D", "A"]
V_vals = [points[pt][0] for pt in cycle]
P_vals = [points[pt][1] for pt in cycle]

plt.figure(figsize=(6, 4))
plt.plot(V_vals, P_vals, marker='o', linestyle='-', color='darkblue')
for pt in points:
    plt.text(points[pt][0], points[pt][1], f" {pt}", fontsize=12, verticalalignment='bottom')

plt.title("p-V Diagram of Thermodynamic Cycle")
plt.xlabel("Volume [m³]")
plt.ylabel("Pressure [Pa]")
plt.grid(True)
plt.tight_layout()
plt.show()

```


```Python
# Program Name: mass_defect_energy.py
# Creation Date: 20250609
# Overview: Compute energy from mass defect using E = mc^2 and convert to MeV

# 定数定義
mass_defect_u = 0.0035                  # 質量欠損 [u]
u_to_kg = 1.7e-27                       # 1 u = 1.7×10⁻²⁷ kg
c = 3.0e8                               # 光速 [m/s]
J_to_MeV = 1.6e-13                      # 1 MeV = 1.6×10⁻¹³ J

# エネルギー計算 [E = Δm * c^2]
mass_defect_kg = mass_defect_u * u_to_kg
energy_J = mass_defect_kg * c**2
energy_MeV = energy_J / J_to_MeV

# 結果表示
print(f"質量欠損 = {mass_defect_u:.4f} u")
print(f"エネルギー = {energy_J:.3e} J")
print(f"エネルギー ≒ {energy_MeV:.2f} MeV")

```



```Python
# Program Name: electron_acceleration.py
# Creation Date: 20250609
# Overview: Compute velocity of charged particle accelerated by electric potential

# 定数定義
e = 1.6e-19         # 電子の電荷 [C]
m = 9.1e-31         # 電子の質量 [kg]
V0 = 100.0          # 加速電圧 [V]（例：100V）

# エネルギー保存則による速度計算
v0 = (2 * e * V0 / m) ** 0.5

# 結果表示
print(f"加速電圧 V0 = {V0} V")
print(f"電子の初速度 v0 = {v0:.2e} m/s")


```


```Python
# Program Name: buoyancy_temperature_difference.py
# Creation Date: 20250609
# Overview: Determine buoyancy condition for hot air using temperature difference

# 定数と記号定義
T = 300.0       # 周囲の温度 [K]（例：27°C ≒ 300K）
dT = 20.0       # 空気球内部の温度上昇 [K]
rho = 1.2       # 外気の密度 [kg/m³]
V = 1.0         # 空気球の体積 [m³]
g = 9.8         # 重力加速度 [m/s²]

# 空気球内の平均密度（状態方程式の比を利用）
rho_bar = rho * T / (T + dT)

# 浮力判定：ρVg > ρ̄Vg
left = rho * V * g
right = rho_bar * V * g
net_force = left - right

# 結果表示
print(f"外気密度 ρ = {rho} kg/m³")
print(f"空気球内密度 ρ̄ = {rho_bar:.3f} kg/m³")
print(f"浮力 = {net_force:.2f} N → {'上昇' if net_force > 0 else '下降'}")

```


```Python
# Program Name: kinetic_energy_from_potential.py
# Creation Date: 20250609
# Overview: Calculate the velocity v0 from electric potential energy using conservation of energy

# 定数定義
e = 1.6e-19       # 電子の電荷 [C]
m = 9.1e-31       # 電子の質量 [kg]
V0 = 200.0        # 電位差 [V]（例：200V加速）

# 速度計算（エネルギー保存則：1/2mv² = eV）
v0 = (2 * e * V0 / m) ** 0.5

# 結果表示
print(f"電位差 V0 = {V0} V")
print(f"速度 v0 = {v0:.2e} m/s")

```



```Python
# Program Name: projectile_rebound_series.py
# Creation Date: 20250609
# Overview: Calculate time and velocity after n bounces of a projectile with energy loss factor e

import math

# パラメータ定義
v0 = 10.0          # 初速度 [m/s]
theta_deg = 45.0   # 発射角度 [deg]
theta = math.radians(theta_deg)
g = 9.8            # 重力加速度 [m/s^2]
e = 0.8            # 反発係数（0 < e < 1）
n = 3              # 反発回数

# (b) 1回目の飛行時間と速度
t1 = (2 * v0 * math.sin(theta)) / g
v1_x = v0 * math.cos(theta)
v1_y = e * v0 * math.sin(theta)

# (c) n回目までの合計時間と速度
tn = ((1 - e**n) / (1 - e)) * t1
vn_x = v0 * math.cos(theta)
vn_y = e**n * v0 * math.sin(theta)

# (d) 総合距離
range_total = (1 / (1 - e)) * (v0**2 * math.sin(2 * theta)) / g

# 結果表示
print(f"(b) t1 = {t1:.3f} s, v1 = ({v1_x:.2f}, {v1_y:.2f}) m/s")
print(f"(c) tn = {tn:.3f} s, vn = ({vn_x:.2f}, {vn_y:.2f}) m/s")
print(f"(d) 総合距離 = {range_total:.3f} m")

```




```Python
# Program Name: mass_charge_ratio_radius.py
# Creation Date: 20250609
# Overview: Compute mass and charge ratios from circular motion in magnetic field

import math

# --- 定数定義 [Physical constants] ---
q = 1.6e-19         # 電荷 [C]
V = 1.0e3           # 加速電圧 [V]
B = 0.2             # 磁束密度 [T]
d1 = 0.02           # 軌道1の直径 [m]
d2 = 0.01           # 軌道2の直径 [m]

# --- カ）m1/m2 = (d1/d2)^2 ---
mass_ratio = (d1 / d2)**2

# --- キ）m1 = 4m2 のとき，q1/q2 = 4(d2/d1)^2 ---
charge_ratio = 4 * (d2 / d1)**2

# --- ケ）質量 m = (d^2 * B^2 * q) / (8V) ---
d = 0.02       # [m] 軌道直径
m_kg = (d**2 * B**2 * q) / (8 * V)
m_u = m_kg / 1.7e-27   # 1 u = 1.7e-27 kg

# --- 結果表示 ---
print(f"(カ) m1/m2 = {mass_ratio:.1f}")
print(f"(キ) q1/q2 = {charge_ratio:.1f}")
print(f"(ケ) 質量 m = {m_kg:.2e} kg ≒ {m_u:.1f} u")

```


```Python
# Program Name: friction_spring_condition.py
# Creation Date: 20250609
# Overview: Evaluate spring compression with friction and velocity

import math

# --- パラメータ設定 [Parameter definitions] ---
m = 0.5            # 質量 [kg]
g = 9.8            # 重力加速度 [m/s²]
k = 20.0           # ばね定数 [N/m]
v = 2.0            # 初速度 [m/s]
mu = 0.3           # 動摩擦係数
mu0 = 0.4          # 静止摩擦係数

# --- (a) すべりはじめるための変位D [critical displacement D] ---
term1 = - (mu * m * g) / k
term2 = math.sqrt((m * v**2) / k + ((mu * m * g / k) ** 2))
D = term1 + term2

# --- (b) 静止限界 [maximum static friction displacement] ---
D_static_limit = (mu0 * m * g) / k

# --- 判定 ---
state = "すべり始める" if D > D_static_limit else "静止を続ける"

# --- 結果表示 ---
print(f"(a) D = {D:.3f} m")
print(f"(b) 静止限界 = {D_static_limit:.3f} m")
print(f"判定：{state}")

```



```Python
# Program Name: inclined_plane_impact_max_distance.py
# Creation Date: 20250609
# Overview: Compute distance x to inclined surface based on launch angle

import math

# 定数定義
v0 = 10.0           # 初速度 [m/s]
g = 9.8             # 重力加速度 [m/s^2]
theta = math.pi / 8  # 角度 θ [rad]

# 計算式：
# x = (√2 * v0² / g) * {-1 + √2 * sin(2θ + π/4)}
term = math.sqrt(2) * v0**2 / g
angle = 2 * theta + math.pi / 4
x = term * (-1 + math.sqrt(2) * math.sin(angle))

# 出力
print(f"発射角 θ = {math.degrees(theta):.1f}°")
print(f"衝突点までの距離 x = {x:.3f} m")

```



```Python
# Program Name: electric_potential_energy_conservation.py
# Creation Date: 20250609
# Overview: Compute velocity of a point charge from potential energy using electric field configuration

import math

# --- 定数定義 [Constants] ---
k = 9.0e9         # クーロン定数 [N·m²/C²]
Q = 1.0e-6        # 電荷量 [C]
q = 1.0e-6        # 試験電荷 [C]
a = 0.10          # 基準距離 [m]
m = 1.0e-3        # 試験電荷の質量 [kg]

# --- 位置x_F = 5a での電位 φ_F ---
r1 = 5 * a + a    # 点電荷 -9Q からの距離
r2 = 5 * a - a    # 点電荷 +4Q からの距離
phi_F = k * (-9 * Q / r1 + 4 * Q / r2)

# --- エネルギー保存則による速度 [Energy conservation to get v] ---
v = math.sqrt(2 * q * abs(phi_F) / m)

# --- 結果表示 ---
print(f"点Fでの電位 φ_F = {phi_F:.2e} V")
print(f"点Pの速度 v = {v:.2f} m/s")

```


```Python
# Program Name: spring_incline_oscillation.py
# Creation Date: 20250609
# Overview: Analyze a mass-spring system on an incline with release and oscillation

import math

# --- 定数定義 [Parameters] ---
m = 0.2           # 小球の質量 [kg]
M = 0.5           # 板の質量 [kg]
k = 10.0          # ばね定数 [N/m]
L = 0.50          # 初期位置 [m]
g = 9.8           # 重力加速度 [m/s^2]
theta_deg = 30    # 傾斜角 [degrees]
theta = math.radians(theta_deg)

# --- 離れる瞬間のx座標範囲 [Release condition] ---
x0_max = L - (2 * (m + M) * g * math.sin(theta)) / k

# --- 運動エネルギー [Kinetic energy at x=L] ---
x0 = x0_max       # 最大範囲でのx0を仮定
K = 0.5 * (L - x0)**2 * k - (m + M) * g * (L - x0) * math.sin(theta)

# --- 単振動の周期と中心位置 [Period and center] ---
T = 2 * math.pi * math.sqrt(M / k)
x_center = L - (m * g * math.sin(theta)) / k

# --- 結果表示 ---
print(f"ばねが離れる直前のx0最大値 = {x0_max:.3f} m")
print(f"そのときの運動エネルギー K = {K:.3f} J")
print(f"単振動の周期 T = {T:.3f} s")
print(f"振動中心 x = {x_center:.3f} m")

```



```Python
# Program Name: electromagnetic_induction_slide.py
# Creation Date: 20250609
# Overview: Analyze electromagnetic induction and forces on a sliding conductor in magnetic field

import math

# --- 定数定義 [Constants] ---
m = 0.1             # 質量 [kg]
g = 9.8             # 重力加速度 [m/s^2]
B = 0.5             # 磁束密度 [T]
L = 0.2             # 棒の長さ [m]
R = 2.0             # 抵抗 [Ω]
theta_deg = 30      # 傾斜角 [degrees]
theta = math.radians(theta_deg)

# --- 問7：電流 I' の計算 ---
v = 3.0             # 棒の速度 [m/s]
E_induced = v * B * L * math.cos(theta)  # 誘導起電力
I_prime = E_induced / R                  # 電流 I'

# --- 問8：つり合い条件より電流計算 ---
I_Bcos = m * g * math.sin(theta) / (B * L)         # I' B L cosθ = mg sinθ より
I_prime_2 = m * g * math.tan(theta) / (B * L)      # tanθ からの別表現

# --- 棒が等速度で滑るための電圧条件 E > ... ---
E_min = m * g * R * math.tan(theta) / (B * L)

# --- 結果表示 ---
print(f"誘導起電力 E = {E_induced:.3f} V")
print(f"電流 I' = {I_prime:.3f} A")
print(f"釣り合い条件からの電流 I' = {I_Bcos:.3f} A")
print(f"tanθ表現からの電流 I' = {I_prime_2:.3f} A")
print(f"等速で滑るために必要な外部電圧 E > {E_min:.3f} V")

```



```Python
# Program Name: doppler_satellite_orbit_radius.py
# Creation Date: 20250609
# Overview: Compute satellite orbital radius using Doppler frequency shift

import math

# --- 定数定義 [Constants] ---
G = 6.674e-11       # 万有引力定数 [m^3/kg/s^2]
M = 5.97e24         # 地球の質量 [kg]
c = 3.0e8           # 光速 [m/s]
f = 1.0e9           # 元の周波数 [Hz]
phi_deg = 60        # 角度 φ [degrees]
phi = math.radians(phi_deg)

# --- ドップラー効果による周波数変化 ---
fp = c / (c - c * math.cos(phi)) * f   # 近づく
fe = c / (c + c * math.cos(phi)) * f   # 遠ざかる

# --- ドップラー式からrを導出（b式の結論） ---
num = (fp + fe) / (fp - fe)            # 周波数比
R = (G * M * R**2 / c**2)**(1/3) * num**(2/3)  # R = [GMR^2/c^2]^{1/3} * (比)^{2/3}

# --- 出力 [Output] ---
print(f"近づくときの fp = {fp:.3e} Hz")
print(f"遠ざかるときの fe = {fe:.3e} Hz")
print(f"fp+fe / fp-fe = {num:.3f}")
print(f"軌道半径 r = {R:.3e} m")

```


```Python
# Program Name: oscillation_magnetic_spring.py
# Creation Date: 20250609
# Overview: Compute T and t0 from electromagnetic spring oscillation with equivalent mass

import math

# --- パラメータ定義 ---
m = 0.10           # 導体の質量 [kg]
C = 1.0e-6         # コンデンサ容量 [F]
B = 0.50           # 磁束密度 [T]
l = 0.20           # 棒の長さ [m]
k = 5.0            # ばね定数 [N/m]

# --- 有効質量の計算 ---
m_eff = m + C * (B * l)**2

# --- 周期と t0 の計算 ---
T = 2 * math.pi * math.sqrt(m_eff / k)
t0 = (math.pi / 2) * math.sqrt(m_eff / k)

# --- 出力 ---
print(f"有効質量 m_eff = {m_eff:.6f} kg")
print(f"振動周期 T = {T:.5f} s")
print(f"位相 π/2 に達する時刻 t0 = {t0:.5f} s")

```


```Python
# Program Name: double_slit_path_difference.py
# Creation Date: 20250609
# Overview: Compute interference conditions for double slit experiment using geometry and wavelength

import math

# --- パラメータ定義 [Parameters] ---
l = 1.0         # スリットからスクリーンまでの距離 [m]
a = 0.001       # スリットAの位置 [m]
b = 0.001       # スリットBの位置 [m]
λ = 6.0e-7      # 波長 [m]
x = 0.005       # スクリーン上の位置 [m]

# --- 問2: 経路差 ΔL = 2xb / l ---
delta_L2 = 2 * x * b / l

# --- 干渉条件（明線）：ΔL = mλ（m: 整数） ---
m2 = round(delta_L2 / λ)

# --- 問3(1): 経路差 ΔL = (b + a - α) * l / b ---
α = 0.0002   # α位置補正 [m]
delta_L3 = (b + a - α) * l / b
m3 = round(delta_L3 / λ)

# --- 出力 [Results] ---
print(f"[問2] 経路差 ΔL = {delta_L2:.4e} m → 明線条件 m = {m2}")
print(f"[問3] 経路差 ΔL = {delta_L3:.4e} m → 明線条件 m = {m3}")

```