{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9c1ee1e6",
   "metadata": {},
   "source": [
    "# PHYS 216 — Assignment 1, Problem 1\n",
    "\n",
    "## Finite line of charge\n",
    "\n",
    "A rod with uniform linear charge density $\\lambda$ lies on the $x$-axis from $-L$ to $+L$. We find the electric field at $P(a,b)$, verify the closed form by numerical integration, and graph the centered limiting cases.\n",
    "\n",
    "For a charge element $dq=\\lambda\\,dx$, the displacement from the element at $(x,0)$ to $P$ is\n",
    "\n",
    "$$\\mathbf r=(a-x)\\hat{\\mathbf i}+b\\hat{\\mathbf j},\\qquad r=\\sqrt{(a-x)^2+b^2}.$$\n",
    "\n",
    "Therefore,\n",
    "\n",
    "$$d\\mathbf E=k\\lambda\\frac{(a-x)\\hat{\\mathbf i}+b\\hat{\\mathbf j}}{[(a-x)^2+b^2]^{3/2}}\\,dx.$$\n",
    "\n",
    "The total charge is $Q=2\\lambda L$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dbb4690b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-19T00:51:09.712450Z",
     "iopub.status.busy": "2026-09-19T00:51:09.712450Z",
     "iopub.status.idle": "2026-09-19T00:51:10.170786Z",
     "shell.execute_reply": "2026-09-19T00:51:10.170786Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "k = 8.9875517923e9  # N m^2 / C^2\n",
    "\n",
    "def analytic_field(lam, L, a, b):\n",
    "    \"\"\"Return (Ex, Ey) for the finite rod, b != 0.\"\"\"\n",
    "    r_right = np.sqrt((a - L)**2 + b**2)\n",
    "    r_left = np.sqrt((a + L)**2 + b**2)\n",
    "    Ex = k * lam * (1/r_right - 1/r_left)\n",
    "    Ey = (k * lam / b) * ((L-a)/r_right + (L+a)/r_left)\n",
    "    return np.array([Ex, Ey])\n",
    "\n",
    "def numerical_field(lam, L, a, b, n=200_001):\n",
    "    \"\"\"Directly integrate dE over x with the trapezoid rule.\"\"\"\n",
    "    x = np.linspace(-L, L, n)\n",
    "    denom = ((a-x)**2 + b**2)**1.5\n",
    "    dEx_dx = k * lam * (a-x) / denom\n",
    "    dEy_dx = k * lam * b / denom\n",
    "    return np.array([np.trapezoid(dEx_dx, x), np.trapezoid(dEy_dx, x)])\n",
    "\n",
    "lam, L, a, b = 1.0e-9, 0.50, 0.20, 0.30\n",
    "Ea = analytic_field(lam, L, a, b)\n",
    "En = numerical_field(lam, L, a, b)\n",
    "print(f\"Analytic E = ({Ea[0]:.6g}, {Ea[1]:.6g}) N/C\")\n",
    "print(f\"Numeric  E = ({En[0]:.6g}, {En[1]:.6g}) N/C\")\n",
    "print(f\"Relative difference = {np.linalg.norm(Ea-En)/np.linalg.norm(Ea):.3e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6ebfd0c",
   "metadata": {},
   "source": [
    "## Closed-form result\n",
    "\n",
    "$$E_x=k\\lambda\\left[\\frac{1}{\\sqrt{(a-L)^2+b^2}}-\\frac{1}{\\sqrt{(a+L)^2+b^2}}\\right],$$\n",
    "\n",
    "$$E_y=\\frac{k\\lambda}{b}\\left[\\frac{L-a}{\\sqrt{(L-a)^2+b^2}}+\\frac{L+a}{\\sqrt{(L+a)^2+b^2}}\\right].$$\n",
    "\n",
    "On the perpendicular bisector, $a=0$, symmetry gives $E_x=0$ and\n",
    "\n",
    "$$\\mathbf E(0,b)=\\frac{kQ}{b\\sqrt{L^2+b^2}}\\hat{\\mathbf j}.$$\n",
    "\n",
    "- If $b\\gg L$: $E_y\\approx kQ/b^2$ (the rod looks like a point charge).\n",
    "- If $b\\ll L$: $E_y\\approx 2k\\lambda/b=\\lambda/(2\\pi\\epsilon_0b)$ (the rod looks infinite)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49bbf21c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-19T00:51:10.172797Z",
     "iopub.status.busy": "2026-09-19T00:51:10.172797Z",
     "iopub.status.idle": "2026-09-19T00:51:10.652921Z",
     "shell.execute_reply": "2026-09-19T00:51:10.652921Z"
    }
   },
   "outputs": [],
   "source": [
    "# Dimensionless graph for the centered case a = 0\n",
    "u = np.logspace(-1.5, 1.5, 500)  # u = b/L\n",
    "exact = 1/(u*np.sqrt(1+u**2))\n",
    "near_line = 1/u\n",
    "far_point = 1/u**2\n",
    "\n",
    "plt.figure(figsize=(8, 5))\n",
    "plt.loglog(u, exact, lw=3, color='#005FBE', label='exact finite rod')\n",
    "plt.loglog(u[u < 0.7], near_line[u < 0.7], '--', lw=2, color='#E50024', label='near: 1/b')\n",
    "plt.loglog(u[u > 1.5], far_point[u > 1.5], '--', lw=2, color='#009B77', label='far: 1/b²')\n",
    "plt.axvline(1, color='#F5A600', lw=2, label='b = L')\n",
    "plt.xlabel('b/L')\n",
    "plt.ylabel(r'$E_y/(kQ/L^2)$')\n",
    "plt.title('Finite rod: line-like nearby, point-like far away')\n",
    "plt.grid(True, which='both', alpha=0.3)\n",
    "plt.legend(frameon=False)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13b6614f",
   "metadata": {},
   "source": [
    "## Optional field map\n",
    "\n",
    "The arrows point away from the positively charged rod. The midpoint symmetry is easy to see: on the $y$-axis, horizontal components cancel."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aeb71530",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-19T00:51:10.652921Z",
     "iopub.status.busy": "2026-09-19T00:51:10.652921Z",
     "iopub.status.idle": "2026-09-19T00:51:10.797783Z",
     "shell.execute_reply": "2026-09-19T00:51:10.797783Z"
    }
   },
   "outputs": [],
   "source": [
    "# Vector field around the rod (arbitrary normalization for visualization)\n",
    "xx, yy = np.meshgrid(np.linspace(-1.4, 1.4, 25), np.linspace(0.12, 1.5, 18))\n",
    "Ex = np.zeros_like(xx)\n",
    "Ey = np.zeros_like(yy)\n",
    "for j in range(xx.shape[0]):\n",
    "    for i in range(xx.shape[1]):\n",
    "        Ex[j, i], Ey[j, i] = analytic_field(1.0, 1.0, xx[j, i], yy[j, i]) / k\n",
    "mag = np.hypot(Ex, Ey)\n",
    "\n",
    "plt.figure(figsize=(8, 5))\n",
    "plt.quiver(xx, yy, Ex/mag, Ey/mag, np.log10(mag), cmap='viridis', pivot='mid')\n",
    "plt.plot([-1, 1], [0, 0], lw=8, color='#005FBE', solid_capstyle='round')\n",
    "plt.text(0, -0.08, 'uniformly charged rod', ha='center', va='top')\n",
    "plt.xlabel('x/L'); plt.ylabel('y/L')\n",
    "plt.title('Direction of the electric field above a finite rod')\n",
    "plt.axis('equal'); plt.ylim(-0.18, 1.55); plt.grid(alpha=0.2)\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}