{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "nonlinear-eq-00",
   "metadata": {},
   "source": [
    "# A shrinking bracket around a pole\n",
    "Compare a continuous zero crossing with a discontinuous sign reversal at exactly the same location. Keep a separate record of spatial width and measured residual on every iteration."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "nonlinear-eq-01",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "location = np.sqrt(2)/4\n",
    "rounds = 20\n",
    "assert 0 < location < 1 and 5 <= rounds <= 35\n",
    "def bisect_record(f, tie_residual):\n",
    "    lo,hi=0.,1.\n",
    "    data=[]\n",
    "    for j in range(rounds):\n",
    "        mid=(lo+hi)/2\n",
    "        if mid==location:\n",
    "            data.append((mid,hi-lo,tie_residual))\n",
    "            break\n",
    "        value=f(mid)\n",
    "        data.append((mid,hi-lo,abs(value)))\n",
    "        if np.signbit(value)==np.signbit(f(lo)):lo=mid\n",
    "        else:hi=mid\n",
    "    return np.array(data)\n",
    "zero=bisect_record(lambda x:x-location,0.)\n",
    "pole=bisect_record(lambda x:1/(x-location),np.inf)\n",
    "regular=np.isfinite(pole[:,2])\n",
    "assert np.allclose(zero[:,:2],pole[:,:2])\n",
    "assert np.allclose(zero[regular,2]*pole[regular,2],1)\n",
    "if not regular[-1]: print(\"Exact midpoint hit: the linear signal vanishes and the reciprocal is undefined.\")\n",
    "print(\"Final width\",zero[-1,1],\"zero residual\",zero[-1,2],\"pole magnitude\",pole[-1,2])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "nonlinear-eq-02",
   "metadata": {},
   "source": [
    "## Change the observable as well as the tolerance\n",
    "Both candidates go through identical midpoints, although only one residual can approach zero. Take two new distances from the candidate and compare how the output scales."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "nonlinear-eq-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,(shape,error)=plt.subplots(1,2,figsize=(10,4),layout=\"constrained\")\n",
    "margin = min(.01,location/2,(1-location)/2)\n",
    "for xs in (np.linspace(0,location-margin,180),np.linspace(location+margin,1,240)):\n",
    "    shape.plot(xs,1/(xs-location),color=\"#b94626\")\n",
    "shape.plot([0,1],[-location,1-location],color=\"#145c71\",label=\"continuous crossing\")\n",
    "shape.plot([],[],color=\"#b94626\",label=\"pole\")\n",
    "shape.set(xlabel=\"x\",ylabel=\"Signal\",ylim=(-10,10),title=\"Same endpoint signs\")\n",
    "shape.legend()\n",
    "j=np.arange(1,len(zero)+1)\n",
    "for data,c,label in [(zero,\"#145c71\",\"absolute zero residual\"),(pole,\"#b94626\",\"absolute pole residual\")]:\n",
    "    error.semilogy(j[regular],data[regular,2],\".-\",color=c,label=label)\n",
    "error.semilogy(j,zero[:,1],\":\",color=\"black\",label=\"bracket width\")\n",
    "error.set(xlabel=\"Iteration\",ylabel=\"Magnitude\",title=\"A width test cannot certify continuity\")\n",
    "error.legend(fontsize=8)\n",
    "for ax in (shape,error):ax.grid(alpha=.2)\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
