電磁気学演習 (理工基礎物理学演習ライブラリ 3)Pythonコード


P3

import numpy as np

# Constants
Q = 1e-9  # Example charge in Coulombs
epsilon_0 = 8.854e-12  # Permittivity of free space in F/m
a = 0.1  # Distance in meters
x = np.linspace(-0.01, 0.01, 1000)  # Displacement in meters

# Force F along AB direction
F = (Q**2) / (4 * np.pi * epsilon_0 * (a**2 + x**2))

# Force f along vertical direction (approximation)
f_approx = (Q**2 * x) / (2 * np.pi * epsilon_0 * a**3)

# Period T for small oscillations
m = 1e-3  # Example mass in kg
T = (2 * np.pi * epsilon_0 * m * a / Q**2)**0.5 * 2 * np.pi * a

# Force f along BC direction (approximation)
f_BC = (Q**2) / (np.pi * epsilon_0 * a**3) * x

# Display results
print("Force F along AB direction:", F)
print("Approximate force f along vertical direction:", f_approx)
print("Period T for small oscillations:", T)
print("Approximate force f along BC direction:", f_BC)


import numpy as np
import matplotlib.pyplot as plt

# 定数 'a' を定義
a = 2

# x の値を生成(a を避ける)
x = np.linspace(-a + 0.01, a - 0.01, 500)

# 関数を定義
y = (1 / (a - x)**2) - (1 / (a + x)**2)

# グラフをプロット
plt.plot(x, y, label=r'$\frac{1}{(a-x)^2} - \frac{1}{(a+x)^2}$')

# タイトルとラベルを追加
plt.title('Plot of the function')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.grid(True)
plt.legend()

# プロットを表示
plt.show()


P4
直線状の分布した電荷
F=(Qλl/(2πεa))×(1/(a^2+l^2)^(1/2))

import numpy as np
import matplotlib.pyplot as plt

# Define constants
Q = 1.0  # Charge Q (Coulombs)
lambda_ = 1.0  # Linear charge density λ (Coulombs per meter)
epsilon = 8.854e-12  # Permittivity of free space ε (F/m)
a = 1.0  # Distance a (meters)

# Generate values for l (length of the charge distribution)
l = np.linspace(0.1, 10, 500)

# Calculate the force F as a function of l
F = (Q * lambda_ * l) / (2 * np.pi * epsilon * a) * (1 / np.sqrt(a**2 + l**2))

# Plotting the force F versus l
plt.plot(l, F, label=r'$F = \frac{Q \lambda l}{2 \pi \epsilon a} \times \frac{1}{\sqrt{a^2 + l^2}}$')

# Adding titles and labels
plt.title('Force due to a Linearly Distributed Charge')
plt.xlabel('Length of the charge distribution l (meters)')
plt.ylabel('Force F (Newtons)')
plt.grid(True)
plt.legend()

# Show the plot
plt.show()

P6

import numpy as np

# Constants
Q = 1e-9  # Example charge in Coulombs
epsilon_0 = 8.854e-12  # Permittivity of free space in F/m
r = 0.1  # Distance in meters
l = 0.01  # Small displacement in meters
theta = np.pi / 4  # Example angle in radians

# Electric Field E1
E1 = (Q / (4 * np.pi * epsilon_0)) * (1 / (r + l)**2 - 1 / (r - l)**2)

# Electric Field E2
E2 = 2 * (Q / (4 * np.pi * epsilon_0)) * (l / (r**2 + l**2)) * np.cos(theta)
E2_approx = (Q * l) / (2 * np.pi * epsilon_0 * (r**2 + l**2)**(3/2))

# Approximation for small x (x << 1)
E1_approx = -(Q * l) / (np.pi * epsilon_0 * r**3)
E2_approx_final = (Q * l) / (2 * np.pi * epsilon_0 * r**3) * (1 - 3/2 * (l**2 / r**2))

# Display results
print("Electric Field E1:", E1)
print("Electric Field E2 (exact):", E2)
print("Electric Field E2 (approximation):", E2_approx)
print("Approximation for E1 when x << 1:", E1_approx)
print("Approximation for E2 when x << 1:", E2_approx_final)

P7

import numpy as np
import matplotlib.pyplot as plt

# Constants
sigma = 1e-6  # Surface charge density (C/m^2)
epsilon_0 = 8.854e-12  # Permittivity of free space (F/m)
R = 1.0  # Radius of the disk (m)

# Function to calculate the electric field E
def electric_field(a):
    return (sigma / (2 * epsilon_0)) * (1/a - 1/np.sqrt(R**2 + a**2))

# Range of 'a' (distance from the disk along the axis)
a_values = np.linspace(0.01, 10, 500)  # Avoid division by zero at a = 0

# Calculate the electric field for each value of 'a'
E_values = electric_field(a_values)

# Plotting the electric field E as a function of 'a'
plt.plot(a_values, E_values, label=r'$E = \frac{\sigma}{2\epsilon_0} \left[\frac{1}{a} - \frac{1}{\sqrt{R^2 + a^2}}\right]$')

# Adding titles and labels
plt.title('Electric Field along the Axis of a Uniformly Charged Disk')
plt.xlabel('Distance from the Disk along the Axis (a) [m]')
plt.ylabel('Electric Field (E) [N/C]')
plt.grid(True)
plt.legend()

# Display the plot
plt.show()

P10

import numpy as np
import matplotlib.pyplot as plt

# Constants
rho_0 = 1e-6  # Charge density in C/m^3
epsilon_0 = 8.854e-12  # Permittivity of free space in F/m
a = 0.1  # Sphere radius in meters

# Range of r values (0 < r < 2a for demonstration)
r = np.linspace(0, 2 * a, 1000)

# Electric field E inside the sphere (r < a)
E_inside = (rho_0 * r) / (3 * epsilon_0)

# Electric field E outside the sphere (r > a)
E_outside = (rho_0 * a**3) / (3 * epsilon_0 * r**2)

# Combined E field considering all regions
E_combined = np.where(r < a, E_inside, E_outside)

# Plotting
plt.figure(figsize=(10, 6))
plt.plot(r, E_combined, label=r'$E$ (Inside & Outside Sphere)')
plt.axvline(x=a, color='red', linestyle='--', label=r'$r = a$')
plt.title('Electric Field as a Function of Radius r')
plt.xlabel('r (meters)')
plt.ylabel('Electric Field E (N/C)')
plt.legend()
plt.grid(True)
plt.show()

p13

import numpy as np

# Vacuum permittivity (F/m)
epsilon_0 = 8.854187817e-12

# Charge density (C/m^3) - assuming a uniform charge density as an example
rho = 1e-6

# Setting up a 3D grid
grid_size = 100
x = np.linspace(-1, 1, grid_size)
y = np.linspace(-1, 1, grid_size)
z = np.linspace(-1, 1, grid_size)
X, Y, Z = np.meshgrid(x, y, z)

# Electric field (simple model - assuming a uniform electric field)
Ex = np.ones((grid_size, grid_size, grid_size))
Ey = np.zeros((grid_size, grid_size, grid_size))
Ez = np.zeros((grid_size, grid_size, grid_size))

# Calculating the divergence
div_E = np.gradient(Ex, axis=0) + np.gradient(Ey, axis=1) + np.gradient(Ez, axis=2)

# Verifying Gauss's law
lhs = div_E
rhs = rho / epsilon_0

# Displaying the results
print("Calculated divergence (∇·E):", lhs)
print("Calculated charge density/ε0:", rhs)
print("Difference between the two:", np.abs(lhs - rhs).max())

p18

import numpy as np
import matplotlib.pyplot as plt

# Constants
Q = 1e-9  # Charge in Coulombs
epsilon_0 = 8.854e-12  # Permittivity of free space in F/m
a = 0.1  # Radius of the sphere in meters

# Define the range of r
r_outside = np.linspace(a, 0.3, 300)  # r > a
r_inside = np.linspace(0, a, 300)  # r < a

# Electric field E
E_outside = Q / (4 * np.pi * epsilon_0 * r_outside**2)
E_inside = Q * r_inside / (4 * np.pi * epsilon_0 * a**3)

# Potential V
V_outside = Q / (4 * np.pi * epsilon_0 * r_outside)
V_inside = Q / (8 * np.pi * epsilon_0 * a**3) * (3 * a**2 - r_inside**2)

# Plotting E vs r
plt.figure(figsize=(12, 6))

plt.subplot(1, 2, 1)
plt.plot(r_outside, E_outside, label='E (r > a)', color='blue')
plt.plot(r_inside, E_inside, label='E (r < a)', color='orange')
plt.axvline(a, color='black', linestyle='--', label='r = a')
plt.xlabel('r (m)')
plt.ylabel('E (N/C)')
plt.title('Electric Field E vs. Distance r')
plt.legend()
plt.grid(True)

# Plotting V vs r
plt.subplot(1, 2, 2)
plt.plot(r_outside, V_outside, label='V (r > a)', color='blue')
plt.plot(r_inside, V_inside, label='V (r < a)', color='orange')
plt.axvline(a, color='black', linestyle='--', label='r = a')
plt.xlabel('r (m)')
plt.ylabel('V (V)')
plt.title('Electric Potential V vs. Distance r')
plt.legend()
plt.grid(True)

plt.tight_layout()
plt.show()

p22

import numpy as np
import matplotlib.pyplot as plt

def potential(x, y, q, x0, y0):
    """電荷qと鏡像電荷の位置(x0, y0)に基づくポテンシャルの計算"""
    r = np.sqrt((x - x0)**2 + (y - y0)**2)
    return q / r

# パラメータの設定
q = 1.0  # 電荷の強さ
x0 = 0.0  # 鏡像電荷のx座標
y0 = 1.0  # 鏡像電荷のy座標

# グリッドの生成
x = np.linspace(-2, 2, 400)
y = np.linspace(-2, 2, 400)
X, Y = np.meshgrid(x, y)

# ポテンシャルの計算
V = potential(X, Y, q, x0, y0) - potential(X, Y, -q, -x0, -y0)

# プロット
plt.figure(figsize=(8, 6))
plt.contourf(X, Y, V, levels=50, cmap='coolwarm')
plt.colorbar(label='Potential')
plt.scatter([x0, -x0], [y0, -y0], color='red', label='Charges')
plt.title('Electric Potential with Image Charges')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()


p27

import numpy as np
import matplotlib.pyplot as plt

# 定数
rho_0 = 1e-6  # 電荷密度 (C/m^3) の例
epsilon_0 = 8.854e-12  # 真空の誘電率 (F/m)
a = 0.1  # 球の半径 (メートル)

# 球の内側の電位 V(r) の定義 (r < a)
def V_inside(r):
    return (rho_0 * a**2 / (3 * epsilon_0)) * (1 - r**3 / (4 * a**3))

# 球の外側の電位 V(r) の定義 (r >= a)
def V_outside(r):
    return (rho_0 * a**3 / (4 * epsilon_0 * r))

# r の範囲の定義
r_values = np.linspace(0, 0.3, 500)  # r を 0 から 0.3 メートルの範囲で定義

# 電位を計算
V_values = np.piecewise(r_values,
                        [r_values <= a, r_values > a],
                        [V_inside, V_outside])

# プロット
plt.figure(figsize=(8, 6))
plt.plot(r_values, V_values, label='Potential V(r)')
plt.axvline(a, color='r', linestyle='--', label='Radius of the sphere (a)')
plt.title('Potential V(r) as a function of radial distance r')
plt.xlabel('Radial distance r (m)')
plt.ylabel('Potential V (V)')
plt.legend()
plt.grid(True)
plt.show()

p40

import numpy as np
import matplotlib.pyplot as plt

def electric_flux_density(x, y, q, x0, y0):
    """点電荷qによる電束密度の計算"""
    epsilon_0 = 8.854e-12  # 真空の誘電率 (F/m)
    r = np.sqrt((x - x0)**2 + (y - y0)**2)
    # 電束密度の計算
    D = q / (4 * np.pi * epsilon_0 * r**2)
    return D

# パラメータの設定
q = 1e-9  # 電荷の強さ (Coulombs)
x0 = 0.0  # 電荷のx座標
y0 = 0.0  # 電荷のy座標

# グリッドの生成
x = np.linspace(-2, 2, 400)
y = np.linspace(-2, 2, 400)
X, Y = np.meshgrid(x, y)

# 電束密度の計算
D = electric_flux_density(X, Y, q, x0, y0)

# プロット
plt.figure(figsize=(8, 6))
plt.contourf(X, Y, D, levels=50, cmap='viridis')
plt.colorbar(label='Electric Flux Density (D)')
plt.scatter(x0, y0, color='red', label='Charge')
plt.title('Electric Flux Density due to a Point Charge')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()


p59

import numpy as np
import matplotlib.pyplot as plt

def biot_savart_infinite_wire(current, distances):
    """ビオ・サバールの法則による無限に長い直線電流の磁場計算"""
    mu_0 = 4 * np.pi * 1e-7  # 真空の透磁率 (H/m)
    B = (mu_0 * current) / (2 * np.pi * distances)  # 磁場の大きさ
    return B

# パラメータの設定
current = 1.0  # 電流 (A)
distances = np.linspace(0.1, 2, 100)  # 観測点までの距離 (m)

# 磁場の計算
B = biot_savart_infinite_wire(current, distances)

# プロット
plt.figure(figsize=(8, 6))
plt.plot(distances, B, label='Magnetic Field (B)')
plt.title('Magnetic Field due to an Infinite Straight Current')
plt.xlabel('Distance from Wire (m)')
plt.ylabel('Magnetic Field (T)')
plt.grid(True)
plt.legend()
plt.show()


p67

from scipy.integrate import quad

def magnetic_field_infinite_wire(current, distance):
    """無限に長い直線電流による磁場の計算"""
    mu_0 = 4 * np.pi * 1e-7  # 真空の透磁率 (H/m)
    return (mu_0 * current) / (2 * np.pi * distance)

def integrand(theta, current, radius):
    """積分の被積分関数"""
    r = np.array([np.cos(theta), np.sin(theta), 0])
    dl = np.array([0, 0, 1])  # 電流要素 (z方向)
    r_vec = r - np.array([0, 0, 0])  # 観測点から電流要素までのベクトル
    r_mag = np.linalg.norm(r_vec)  # rの大きさ
    dB = np.cross(dl, r_vec) / r_mag**3
    return np.linalg.norm(dB)

def ampere_law_integral(current, radius):
    """アンペールの法則による積分"""
    result, _ = quad(integrand, 0, 2 * np.pi, args=(current, radius))
    return result

# パラメータの設定
current = 1.0  # 電流 (A)
radius = 1.0   # 半径 (m)

# 積分の計算
integral_result = ampere_law_integral(current, radius)
B_integral = magnetic_field_infinite_wire(current, radius)

print("アンペールの法則に基づく積分結果:", integral_result)
print("ビオ・サバールの法則による磁場:", B_integral)




P44



import numpy as np
import matplotlib.pyplot as plt

# Constants
Q = 1e-6         # Charge in Coulombs
epsilon_0 = 8.854e-12  # Permittivity of free space (ε0) in F/m
epsilon = epsilon_0    # ε = ε0 as given
a = 1e-2        # Inner radius of the first shell in meters
c = 2e-2        # Outer radius of the first shell in meters
d = 3e-2        # Outer radius of the second shell in meters

# Distance range for r
r = np.linspace(0, 0.1, 1000)  # r from 0 to 0.1 meters

# Electric field calculation
E = np.zeros_like(r)

# For region a < r < c
mask1 = (r > a) & (r < c)
E[mask1] = Q / (4 * np.pi * epsilon_0 * r[mask1]**2)

# For region c < r < d (Since ε = ε0, the formula remains the same)
mask2 = (r > c) & (r < d)
E[mask2] = Q / (4 * np.pi * epsilon_0 * r[mask2]**2)

# For region r > d
mask3 = (r > d)
E[mask3] = Q / (4 * np.pi * epsilon_0 * r[mask3]**2)

# Plotting the electric field E(r)
plt.figure(figsize=(8, 5))
plt.plot(r, E, label=r'$E(r)$')
plt.xlabel(r'Distance $r$ [m]')
plt.ylabel(r'Electric Field $E(r)$ [V/m]')
plt.title('Electric Field as a Function of Distance $r$')
plt.grid(True)
plt.legend()
plt.show()

P99

import numpy as np
import matplotlib.pyplot as plt

def magnetic_field_inside_sphere(magnetization, radius, distances):
    """磁性体球内部の磁場の計算"""
    mu_0 = 4 * np.pi * 1e-7  # 真空の透磁率 (H/m)
    chi_m = (magnetization * radius**3) / (4 * np.pi)  # 磁化率
    B_in = (3 * mu_0 * chi_m) / (4 * np.pi * distances**3)  # 磁場の大きさ
    return B_in

def magnetic_field_outside_sphere(external_field, radius, distances):
    """磁性体球外部の磁場の計算"""
    mu_0 = 4 * np.pi * 1e-7  # 真空の透磁率 (H/m)
    B_out = external_field * (radius**3 / distances**3)  # 磁場の大きさ
    return B_out

# パラメータの設定
magnetization = 1.0  # 磁化 (A/m)
radius = 1.0         # 磁性体球の半径 (m)
external_field = 1.0 # 外部の均一磁場 (T)
distances = np.linspace(0.1, 2, 100)  # 距離 (m)

# 磁場の計算
B_in = magnetic_field_inside_sphere(magnetization, radius, distances[distances <= radius])
B_out = magnetic_field_outside_sphere(external_field, radius, distances[distances > radius])

# プロット
plt.figure(figsize=(10, 6))
plt.plot(distances[distances <= radius], B_in, label='Inside Sphere')
plt.plot(distances[distances > radius], B_out, label='Outside Sphere')
plt.axvline(x=radius, color='gray', linestyle='--', label='Radius')
plt.title('Magnetic Field of a Magnetic Sphere')
plt.xlabel('Distance from Center (m)')
plt.ylabel('Magnetic Field (T)')
plt.legend()
plt.grid(True)
plt.show()

p109

import numpy as np
import matplotlib.pyplot as plt

# 定数
mu_0 = 4 * np.pi * 1e-7  # 真空の透磁率 (H/m)
I = 1.0  # 電流 (A)
N = 100  # コイルの巻数
R = 0.05  # コイルの半径 (メートル)

# 磁束密度 B(z) の定義
def B(z, a):
    return (mu_0 * N * I * R**2) / (2 * (R**2 + z**2)**(3/2))

# z の範囲の定義
z_values = np.linspace(-0.2, 0.2, 500)  # z を -0.2 から 0.2 メートルの範囲で定義

# B(z) の計算
a_values = [0.01, 0.05, 0.1]  # 半径 a の値のリスト
for a in a_values:
    B_values = B(z_values, a)
    plt.plot(z_values, B_values, label=f'a = {a} m')

# プロット
plt.title('Magnetic Flux Density B(z) as a function of distance z')
plt.xlabel('Distance z (m)')
plt.ylabel('Magnetic Flux Density B (T)')
plt.legend()
plt.grid(True)
plt.show()

p134

import numpy as np
import matplotlib.pyplot as plt

# パラメータの設定
E0 = 1.0           # 電場の振幅 (V/m)
B0 = 1.0           # 磁場の振幅 (T)
wavelength = 1.0   # 波長 (m)
frequency = 1.0    # 周波数 (Hz)
k = 2 * np.pi / wavelength  # 波数
omega = 2 * np.pi * frequency  # 角周波数

# 空間と時間の配列
x = np.linspace(0, 2 * wavelength, 500)  # 空間 (m)
t = np.linspace(0, 2 / frequency, 500)   # 時間 (s)

# 電場と磁場の計算
X, T = np.meshgrid(x, t)
E = E0 * np.cos(k * X - omega * T)  # 電場
B = B0 * np.cos(k * X - omega * T)  # 磁場

# プロット
fig, axs = plt.subplots(2, 1, figsize=(10, 10))

# 電場のプロット
c = axs[0].contourf(X, T, E, cmap='RdBu', levels=100)
axs[0].set_title('Electric Field E(x, t)')
axs[0].set_xlabel('Position (m)')
axs[0].set_ylabel('Time (s)')
fig.colorbar(c, ax=axs[0])

# 磁場のプロット
c = axs[1].contourf(X, T, B, cmap='RdBu', levels=100)
axs[1].set_title('Magnetic Field B(x, t)')
axs[1].set_xlabel('Position (m)')
axs[1].set_ylabel('Time (s)')
fig.colorbar(c, ax=axs[1])

plt.tight_layout()
plt.show()


p135

import numpy as np
import matplotlib.pyplot as plt

def fresnel_reflectance_transmittance(theta_i_deg, n1, n2):
    """Calculate Fresnel reflectance and transmittance."""
    # Convert incidence angle to radians
    theta_i = np.radians(theta_i_deg)
    
    # Calculate transmission angle using Snell's law
    theta_t = np.arcsin(n1 / n2 * np.sin(theta_i))
    
    # Calculate reflectance (s-polarized and p-polarized)
    Rs = np.abs((n1 * np.cos(theta_i) - n2 * np.cos(theta_t)) / 
                (n1 * np.cos(theta_i) + n2 * np.cos(theta_t)))**2
    Rp = np.abs((n2 * np.cos(theta_i) - n1 * np.cos(theta_t)) / 
                (n2 * np.cos(theta_i) + n1 * np.cos(theta_t)))**2
    
    # Calculate transmittance (s-polarized and p-polarized)
    Ts = 1 - Rs
    Tp = 1 - Rp
    
    return Rs, Rp, Ts, Tp

# Parameters
n1 = 1.0  # Refractive index of the incident medium (air)
n2 = 1.5  # Refractive index of the transmitting medium (e.g., glass)

# Range of incidence angles
theta_i_deg = np.linspace(0, 90, 500)

# Compute reflectance and transmittance
Rs, Rp, Ts, Tp = fresnel_reflectance_transmittance(theta_i_deg, n1, n2)

# Plot
plt.figure(figsize=(12, 6))

# Plot reflectance
plt.subplot(1, 2, 1)
plt.plot(theta_i_deg, Rs, label='Rs (s-polarized)', color='blue')
plt.plot(theta_i_deg, Rp, label='Rp (p-polarized)', color='red')
plt.xlabel('Incident Angle (degrees)')
plt.ylabel('Reflectance')
plt.title('Fresnel Reflectance')
plt.legend()
plt.grid(True)

# Plot transmittance
plt.subplot(1, 2, 2)
plt.plot(theta_i_deg, Ts, label='Ts (s-polarized)', color='blue')
plt.plot(theta_i_deg, Tp, label='Tp (p-polarized)', color='red')
plt.xlabel('Incident Angle (degrees)')
plt.ylabel('Transmittance')
plt.title('Fresnel Transmittance')
plt.legend()
plt.grid(True)

plt.tight_layout()
plt.show()


p136

import numpy as np
import matplotlib.pyplot as plt

def skin_depth(resistivity, frequency, permeability):
    """Calculate skin depth based on resistivity, frequency, and permeability."""
    omega = 2 * np.pi * frequency  # Angular frequency
    delta = np.sqrt(2 * resistivity / (omega * permeability))  # Skin depth
    return delta

# Parameters
resistivity = 1.68e-8  # Resistivity of copper (ohm meter)
frequency = np.logspace(1, 10, 500)  # Frequency range from 10 Hz to 10 GHz
permeability = 4 * np.pi * 1e-7  # Permeability of free space (H/m)

# Calculate skin depth
delta = skin_depth(resistivity, frequency, permeability)

# Plot
plt.figure(figsize=(10, 6))
plt.loglog(frequency, delta, label='Skin Depth', color='blue')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Skin Depth (m)')
plt.title('Skin Depth vs. Frequency')
plt.grid(True, which='both', linestyle='--', linewidth=0.5)
plt.legend()
plt.show()

p141

import numpy as np
import matplotlib.pyplot as plt

def cutoff_frequency(m, n, a, b, c):
    """Calculate the cutoff frequency for TE and TM modes in a rectangular waveguide."""
    f_c = (1 / (2 * np.pi)) * np.sqrt((m * np.pi / a)**2 + (n * np.pi / b)**2) * c
    return f_c

def propagation_constant(f, m, n, a, b, c):
    """Calculate the propagation constant for TE and TM modes in a rectangular waveguide."""
    k = 2 * np.pi * f / c
    beta = np.sqrt(k**2 - (m * np.pi / a)**2 - (n * np.pi / b)**2)
    return beta

# Parameters
a = 0.05  # Width of the waveguide (meters)
b = 0.03  # Height of the waveguide (meters)
c = 3e8    # Speed of light in vacuum (m/s)
frequency_range = np.linspace(1e9, 10e9, 500)  # Frequency range from 1 GHz to 10 GHz

# Mode indices
m = 1
n = 0

# Calculate cutoff frequencies and propagation constants
f_c = cutoff_frequency(m, n, a, b, c)
beta = propagation_constant(frequency_range, m, n, a, b, c)

# Plot
plt.figure(figsize=(12, 6))

# Plot cutoff frequency
plt.subplot(1, 2, 1)
plt.axvline(f_c, color='red', linestyle='--', label=f'Cutoff Frequency ({m},{n})')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Propagation Constant (rad/m)')
plt.title('Propagation Constant vs. Frequency')
plt.grid(True)
plt.legend()

# Plot propagation constant
plt.subplot(1, 2, 2)
plt.plot(frequency_range, beta, label=f'β for TE_{m}{n}')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Propagation Constant (rad/m)')
plt.title('Propagation Constant vs. Frequency')
plt.grid(True)
plt.legend()

plt.tight_layout()
plt.show()

p143

import numpy as np
import matplotlib.pyplot as plt

def calculate_distribution(L, C, f, length, z, V_plus, V_minus):
    """Calculate voltage and current distribution along a lossless transmission line."""
    omega = 2 * np.pi * f  # Angular frequency
    beta = omega * np.sqrt(L * C)  # Phase constant
    Z0 = np.sqrt(L / C)  # Characteristic impedance

    # Calculate voltage and current along the transmission line
    V = V_plus * np.exp(-1j * beta * z) + V_minus * np.exp(1j * beta * z)
    I = (V_plus / Z0) * np.exp(-1j * beta * z) - (V_minus / Z0) * np.exp(1j * beta * z)
    
    return np.abs(V), np.abs(I), np.angle(V), np.angle(I)

# Parameters
L = 1e-6  # Inductance per unit length (H/m)
C = 1e-12  # Capacitance per unit length (F/m)
f = 1e9  # Frequency (Hz)
length = 1  # Length of the transmission line (meters)
z = np.linspace(0, length, 500)  # Position along the transmission line

# Incident and reflected voltages
V_plus = 1  # Incident voltage (V)
V_minus = 0  # Reflected voltage (V)

# Calculate voltage and current distributions
V, I, V_phase, I_phase = calculate_distribution(L, C, f, length, z, V_plus, V_minus)

# Plot
plt.figure(figsize=(12, 6))

# Plot voltage magnitude and phase
plt.subplot(2, 2, 1)
plt.plot(z, V, label='Voltage Magnitude')
plt.xlabel('Position along Transmission Line (m)')
plt.ylabel('Voltage (V)')
plt.title('Voltage Magnitude along Transmission Line')
plt.grid(True)

plt.subplot(2, 2, 2)
plt.plot(z, V_phase, label='Voltage Phase', color='red')
plt.xlabel('Position along Transmission Line (m)')
plt.ylabel('Phase (radians)')
plt.title('Voltage Phase along Transmission Line')
plt.grid(True)

# Plot current magnitude and phase
plt.subplot(2, 2, 3)
plt.plot(z, I, label='Current Magnitude')
plt.xlabel('Position along Transmission Line (m)')
plt.ylabel('Current (A)')
plt.title('Current Magnitude along Transmission Line')
plt.grid(True)

plt.subplot(2, 2, 4)
plt.plot(z, I_phase, label='Current Phase', color='red')
plt.xlabel('Position along Transmission Line (m)')
plt.ylabel('Phase (radians)')
plt.title('Current Phase along Transmission Line')
plt.grid(True)

plt.tight_layout()
plt.show()





P154



import numpy as np
import matplotlib.pyplot as plt

# Constants
lambda_ = 1  # Line charge density
a = 1  # Radius of the disk
epsilon_0 = 8.854e-12  # Permittivity of free space

# Define the range of r
r = np.linspace(0.01, 10, 1000)  # Avoid r=0 to prevent division by zero

# Calculate Electric Field (E)
E = (lambda_ * a * r) / (2 * epsilon_0 * (r**2 + a**2)**(3/2))

# Calculate Potential (V)
V = (lambda_ * a) / (2 * epsilon_0 * (r**2 + a**2)**(1/2))

# Plotting
plt.figure(figsize=(12, 6))

# Plot E
plt.subplot(1, 2, 1)
plt.plot(r, E, label=r'$E(r) = \frac{\lambda a r}{2 \epsilon_0 (r^2 + a^2)^{3/2}}$')
plt.title("Electric Field E vs r")
plt.xlabel("r")
plt.ylabel("E")
plt.legend()
plt.grid(True)

# Plot V
plt.subplot(1, 2, 2)
plt.plot(r, V, label=r'$V(r) = \frac{\lambda a}{2 \epsilon_0 (r^2 + a^2)^{1/2}}$')
plt.title("Potential V vs r")
plt.xlabel("r")
plt.ylabel("V")
plt.legend()
plt.grid(True)

plt.tight_layout()
plt.show()





P220

import numpy as np
import matplotlib.pyplot as plt

# Constants
B = 0.5  # Magnetic field in Tesla
v = 10   # Velocity in meters per second
a = 4    # Length a in meters
b = 2    # Length b in meters

# Time ranges based on the piecewise functions
t1 = np.linspace(0, b/v, 500)
t2 = np.linspace(b/v, a/v, 500)
t3 = np.linspace(a/v, (a+b)/v, 500)
t4 = np.linspace((a+b)/v, (a+b)/v + 5, 500)

# Phi and e for each time interval
Phi1 = (B * (v * t1)**2) / 2
e1 = -v**2 * B * t1

Phi2 = np.full_like(t2, B * b**2 / 2)
e2 = np.zeros_like(t2)

Phi3 = B * (b**2 - (v * t3 - a)**2) / 2
e3 = B * (v * t3 - a) * v

Phi4 = np.zeros_like(t4)
e4 = np.zeros_like(t4)

# Combine all pieces for Phi and e
t = np.concatenate([t1, t2, t3, t4])
Phi = np.concatenate([Phi1, Phi2, Phi3, Phi4])
e = np.concatenate([e1, e2, e3, e4])

# Plotting
plt.figure(figsize=(12, 8))

# Plot Phi(t)
plt.subplot(2, 1, 1)
plt.plot(t, Phi, label=r'$\Phi(t)$')
plt.title("Magnetic Flux (Φ) vs Time (t)")
plt.xlabel("Time (t) [s]")
plt.ylabel("Magnetic Flux (Φ) [Wb]")  # Weber (Wb) is the unit of magnetic flux
plt.grid(True)
plt.legend()

# Plot e(t)
plt.subplot(2, 1, 2)
plt.plot(t, e, label=r'$e(t)$', color='orange')
plt.title("Induced EMF (e) vs Time (t)")
plt.xlabel("Time (t) [s]")
plt.ylabel("Induced EMF (e) [V]")  # Volt (V) is the unit of electromotive force (EMF)
plt.grid(True)
plt.legend()

plt.tight_layout()
plt.show()

この記事が気に入ったらサポートをしてみませんか?