|
| 1 | +""" |
| 2 | +Calculate the magnetic field (B) produced by a long straight current-carrying |
| 3 | +conductor at a distance r from the wire in free space. |
| 4 | +
|
| 5 | +Equation for calculating magnetic field: |
| 6 | +B = (μ₀ * I) / (2 * π * r) |
| 7 | +
|
| 8 | +where: |
| 9 | +B = Magnetic field (Tesla, T) |
| 10 | +μ₀ = Permeability of free space (4π × 10⁻⁷ T·m/A) |
| 11 | +I = Current (Amperes, A) |
| 12 | +r = Perpendicular distance from the wire (meters, m) |
| 13 | +
|
| 14 | +https://en.wikipedia.org/wiki/Biot–Savart_law |
| 15 | +""" |
| 16 | + |
| 17 | +import math |
| 18 | + |
| 19 | +# Magnetic constant (Permeability of free space) in T·m/A |
| 20 | +mu_0 = 4 * math.pi * 1e-7 |
| 21 | + |
| 22 | + |
| 23 | +def magnetic_field(current: float, distance: float, permeability: float = mu_0) -> float: |
| 24 | + """ |
| 25 | + Args: |
| 26 | + current: electric current through the wire (Amperes, A) |
| 27 | + distance: perpendicular distance from the wire (meters, m) |
| 28 | + permeability: permeability of the medium (T·m/A), |
| 29 | + default is free space permeability (μ₀) |
| 30 | +
|
| 31 | + returns: |
| 32 | + the magnetic field strength at the given point (Tesla, T) |
| 33 | +
|
| 34 | + >>> magnetic_field(current=10, distance=0.05) |
| 35 | + 3.9999999999999996e-05 |
| 36 | + >>> magnetic_field(current=5, distance=0.1) |
| 37 | + 1.0e-05 |
| 38 | + >>> magnetic_field(current=0, distance=0.1) |
| 39 | + 0.0 |
| 40 | + >>> magnetic_field(current=-5, distance=0.1) |
| 41 | + Traceback (most recent call last): |
| 42 | + ... |
| 43 | + ValueError: Impossible current |
| 44 | + >>> magnetic_field(current=5, distance=-0.1) |
| 45 | + Traceback (most recent call last): |
| 46 | + ... |
| 47 | + ValueError: Impossible distance |
| 48 | + >>> magnetic_field(current=5, distance=0) |
| 49 | + Traceback (most recent call last): |
| 50 | + ... |
| 51 | + ZeroDivisionError: Distance cannot be zero |
| 52 | + """ |
| 53 | + |
| 54 | + if current < 0: |
| 55 | + raise ValueError("Impossible current") |
| 56 | + if distance < 0: |
| 57 | + raise ValueError("Impossible distance") |
| 58 | + if distance == 0: |
| 59 | + raise ZeroDivisionError("Distance cannot be zero") |
| 60 | + |
| 61 | + return (permeability * current) / (2 * math.pi * distance) |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + import doctest |
| 66 | + |
| 67 | + doctest.testmod() |
0 commit comments