{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "ea873303-4ac4-4aad-8a85-c9fee4f6cbea", "metadata": {}, "outputs": [], "source": [ "\n", "\"\"\"\n", " mylegendre(m, x)\n", "\n", "Calculate Legendre polynomial P_n(x) using the recurrence relation \n", "(n+1)P_{n+1}(x) = (2*n+1)*x*P_n(x) - n*P_{n-1}(x), and P_0(x) = 1, P_1(x) = x\n", "\"\"\"\n", "function mylegendre(m, x)\n", "\n", " pp = 1\n", " if m == 0\n", " return pp\n", " end\n", "\n", " pc = x\n", " if m == 1\n", " return pc\n", " end\n", "\n", " for n = 1:(m-1)\n", " # pn = (2*n + 1)/(n + 1) * x * pc - n/(n + 1) * pp\n", " # pp = pc\n", " # pc = pn\n", " pc, pp = (2*n + 1)/(n + 1) * x * pc - n/(n + 1) * pp, pc\n", " end\n", "\n", " return pc\n", "end" ] }, { "cell_type": "code", "execution_count": null, "id": "2d62ab24-fe9c-41d3-8c92-70f69cdc3e7d", "metadata": {}, "outputs": [], "source": [ "\n", "@show mylegendre(3, 0.0); # must be 0\n", "@show mylegendre(3, -1.0); # must be -1" ] }, { "cell_type": "code", "execution_count": null, "id": "21724284-6f4b-4932-ae47-77513f13236a", "metadata": {}, "outputs": [], "source": [ "\n", "@time mylegendre(1, 1.0)" ] }, { "cell_type": "code", "execution_count": null, "id": "779f73fc-be4b-4d35-bc4f-edcb60f75aa8", "metadata": {}, "outputs": [], "source": [ "\n", "@time mylegendre(51, -1.0)" ] }, { "cell_type": "code", "execution_count": null, "id": "a37b5850-fd54-4c43-b82b-defdca4a0b61", "metadata": {}, "outputs": [], "source": [ "\n", "np = 100\n", "x = range(-1.0, 1.0, np);" ] }, { "cell_type": "code", "execution_count": null, "id": "b2605dbc-fb47-4552-a614-3f27ddac0b9c", "metadata": {}, "outputs": [], "source": [ "\n", "using PyPlot" ] }, { "cell_type": "code", "execution_count": null, "id": "80298906-317d-4276-8e7f-67465812c82d", "metadata": {}, "outputs": [], "source": [ "\n", "for n = [2, 3, 5, 7]\n", " plot(x, mylegendre.(n, x), label=L\"P_{%$n}(x)\")\n", "end\n", "\n", "grid(true)\n", "title(\"Legendre polynomials\")\n", "xlabel(\"x\")\n", "ylabel(L\"P_n(x)\")\n", "legend();" ] }, { "cell_type": "code", "execution_count": null, "id": "f884dcee-fd9a-4088-bd7d-6271bf353a08", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Julia 1.11.6", "language": "julia", "name": "julia-1.11" }, "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "1.11.6" } }, "nbformat": 4, "nbformat_minor": 5 }