{
    "nbformat": 4,
    "nbformat_minor": 5,
    "metadata": {
        "kernelspec": {
            "display_name": "Python",
            "language": "python",
            "name": "python"
        },
        "language_info": {
            "name": "python"
        }
    },
    "cells": [
        {
            "id": "d12e7a0a",
            "cell_type": "markdown",
            "source": "<div class='alert alert-warning'>\n\nSciPy's interactive examples with Jupyterlite are experimental and may not always work as expected. Execution of cells containing imports may result in large downloads (up to 60MB of content for the first import from SciPy). Load times when importing from SciPy may take roughly 10-20 seconds. If you notice any problems, feel free to open an [issue](https://github.com/scipy/scipy/issues/new/choose).\n\n</div>",
            "metadata": {}
        },
        {
            "id": "5f401ee7",
            "cell_type": "markdown",
            "source": "To produce a quintic barycentric interpolant approximating the function\n$\\sin x$, and its first four derivatives, using six randomly-spaced\nnodes in $(0, \\pi/2)$:\n",
            "metadata": {}
        },
        {
            "id": "3c27a95d",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import BarycentricInterpolator\nrng = np.random.default_rng()\nxi = rng.random(6) * np.pi/2\nf, f_d1, f_d2, f_d3, f_d4 = np.sin, np.cos, lambda x: -np.sin(x), lambda x: -np.cos(x), np.sin\nP = BarycentricInterpolator(xi, f(xi), random_state=rng)\nfig, axs = plt.subplots(5, 1, sharex=True, layout='constrained', figsize=(7,10))\nx = np.linspace(0, np.pi, 100)\naxs[0].plot(x, P(x), 'r:', x, f(x), 'k--', xi, f(xi), 'xk')\naxs[1].plot(x, P.derivative(x), 'r:', x, f_d1(x), 'k--', xi, f_d1(xi), 'xk')\naxs[2].plot(x, P.derivative(x, 2), 'r:', x, f_d2(x), 'k--', xi, f_d2(xi), 'xk')\naxs[3].plot(x, P.derivative(x, 3), 'r:', x, f_d3(x), 'k--', xi, f_d3(xi), 'xk')\naxs[4].plot(x, P.derivative(x, 4), 'r:', x, f_d4(x), 'k--', xi, f_d4(xi), 'xk')\naxs[0].set_xlim(0, np.pi)\naxs[4].set_xlabel(r\"$x$\")\naxs[4].set_xticks([i * np.pi / 4 for i in range(5)],\n                  [\"0\", r\"$\\frac{\\pi}{4}$\", r\"$\\frac{\\pi}{2}$\", r\"$\\frac{3\\pi}{4}$\", r\"$\\pi$\"])\nfor ax, label in zip(axs, (\"$f(x)$\", \"$f'(x)$\", \"$f''(x)$\", \"$f^{(3)}(x)$\", \"$f^{(4)}(x)$\")):\n    ax.set_ylabel(label)\nlabels = ['Interpolation nodes', 'True function $f$', 'Barycentric interpolation']\naxs[0].legend(axs[0].get_lines()[::-1], labels, bbox_to_anchor=(0., 1.02, 1., .102),\n              loc='lower left', ncols=3, mode=\"expand\", borderaxespad=0., frameon=False)\nplt.show()",
            "outputs": []
        },
        {
            "id": "3bea62fa",
            "cell_type": "markdown",
            "source": "Next, we show how using Chebyshev points of the second kind avoids the avoids the\nRunge phenomenon. In this example, we also compute the weights explicitly.\n",
            "metadata": {}
        },
        {
            "id": "e5c9c78e",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "n = 20\ndef f(x): return np.abs(x) + 0.5*x - x**2\ni = np.arange(n)\nx_cheb = np.cos(i*np.pi/(n - 1))  # Chebyshev points on [-1, 1]\nw_i_cheb = (-1.)**i  # Explicit formula for weights of Chebyshev points\nw_i_cheb[[0, -1]] /= 2\np_cheb = BarycentricInterpolator(x_cheb, f(x_cheb), wi=w_i_cheb)\nx_equi = np.linspace(-1, 1, n)\np_equi = BarycentricInterpolator(x_equi, f(x_equi))\nxx = np.linspace(-1, 1, 1000)\nfig, ax = plt.subplots()\nax.plot(xx, f(xx), label=\"Original Function\")\nax.plot(xx, p_cheb(xx), \"--\", label=\"Chebshev Points\")\nax.plot(xx, p_equi(xx), \"--\", label=\"Equally Spaced Points\")\nax.set(xlabel=\"$x$\", ylabel=\"$f(x)$\", xlim=[-1, 1])\nax.legend()\nplt.show()",
            "outputs": []
        }
    ]
}