もとネタは、’Computational Physics All in One Handbook with Python: Electromagnetism’という本。 Pythonのソースが記載されているので、参考にした。
3次元空間に配置された3個の点電荷それぞれに働くクーロン力を図示する。 点電荷の位置は、赤=(2,0,0)、青=(-2,0,0)、緑=(0,0,3)、電荷量は、赤=5e-5、青=-5e-5、緑=7e-5とする。
クーロン力は、左の式で算出できる。
数式はMathJax-Latex使って書こうと思ったけど、めちゃくちゃ面倒だからやめた。
ソース
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
## Python 3.12.2, numpy 2.2.3, matplotlib 3.10.1 import numpy as np import matplotlib.pyplot as plt # 3D座標設定 def coordinate_3d(axes, range_x, range_y, range_z): axes.set_xlabel("x", fontsize=16) axes.set_ylabel("y", fontsize=16) axes.set_zlabel("z", fontsize=16) axes.set_xlim(range_x[0], range_x[1]) axes.set_ylim(range_y[0], range_y[1]) axes.set_zlim(range_z[0], range_z[1]) #3D グリッドの描画 def grid_3d(axes, range_x, range_y, range_z): x, y, z = np.mgrid[range_x[0]: range_x[1]: 11j, range_y[0]: range_y[1]: 11j, range_z[0]: range_z[1]: 11j] axes.scatter(x, y, z, s=0.2, color='red') #3Dベクトルの描画 def visual_vector_3d(axes, loc, vector, color='red'): axes.quiver(loc[0], loc[1], loc[2], vector[0], vector[1], vector[2], color = color, length = 1, arrow_length_ratio = 0.2) axes.view_init(elev=0, azim=90) #電荷の描画 def charge_3d(axes, pos, col): axes.scatter(pos[0], pos[1], pos[2], s=10, color=col) #クーロン力 def calculate_coulombs_force_vectorized(charges, positions): num_charges = len(charges) forces = np.zeros_like(positions) for i in range(num_charges): for j in range(num_charges): if i!=j: r_vec = positions[j]-positions[i] r_mag = np.linalg.norm(r_vec) if r_mag>1e-12: r_hat = r_vec/r_mag #方向を表す単位ベクトル force_mag = -k_e*charges[i]*charges[j]/(r_mag**2) forces[i] += force_mag*r_hat return forces #クーロン定数 1/4πε0 k_e = 8.9875517873681764e9 #電荷量 charges = np.array([5e-5, -5e-5, 7e-5]) #電荷の位置 positions = np.array([[2.0, 0.0, 0.0], [-2.0, 0.0, 0.0], [0.0, 0.0, 3.0]]) #クーロン力の計算 net_forces = calculate_coulombs_force_vectorized(charges, positions) #クーロン力の3D表示 fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') coordinate_3d(ax, [-5, 5], [-5, 5], [-5, 5]) visual_vector_3d(ax, positions[0], net_forces[0], 'red') visual_vector_3d(ax, positions[1], net_forces[1], 'blue') visual_vector_3d(ax, positions[2], net_forces[2], 'green') charge_3d(ax, positions[0], 'red') charge_3d(ax, positions[1], 'blue') charge_3d(ax, positions[2], 'green') grid_3d(ax, [-5, 5], [-5, 5], [-5, 5]) plt.show() |
表示結果
あまり見やすくないけど、視点を変えながら見ると多少解り易い。