From 7036c84cb5d9f92f343d3c9dcb8ee9eddb9b5f75 Mon Sep 17 00:00:00 2001 From: Pablito Date: Tue, 3 Dec 2024 11:19:20 +0100 Subject: [PATCH] Implemented Legendre polynomial computation algorithm Added an algorithm that calculates the coefficients of the Legendre polynomial of degree n using the recurrence relation --- maths/polynomials/legendre.py | 60 +++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 maths/polynomials/legendre.py diff --git a/maths/polynomials/legendre.py b/maths/polynomials/legendre.py new file mode 100644 index 000000000..8bd3fdb56 --- /dev/null +++ b/maths/polynomials/legendre.py @@ -0,0 +1,60 @@ +from numpy.polynomial import Polynomial +from math import factorial +import pytest + + +def legendre(n: int) -> list[float]: + """ + Compute the coefficients of the nth Legendre polynomial. + + The Legendre polynomials are solutions to Legendre's differential equation + and are widely used in physics and engineering. + + Parameters: + n (int): The order of the Legendre polynomial. + + Returns: + list[float]: Coefficients of the polynomial in ascending order of powers. + """ + p = (1 / (factorial(n) * (2 ** n))) * (Polynomial([-1, 0, 1]) ** n) + return p.deriv(n).coef.tolist() + + +def jsp(): + print(legendre(1)) + print(legendre(2)) + print(legendre(3)) + print(legendre(4)) + + +jsp() + + +def test_legendre_0(): + """Test the 0th Legendre polynomial.""" + assert legendre(0) == [1.0], "The 0th Legendre polynomial should be [1.0]" + + +def test_legendre_1(): + """Test the 1st Legendre polynomial.""" + assert legendre(1) == [0.0, 1.0], "The 1st Legendre polynomial should be [0.0, 1.0]" + + +def test_legendre_2(): + """Test the 2nd Legendre polynomial.""" + assert legendre(2) == [-0.5, 0.0, 1.5], "The 2nd Legendre polynomial should be [-0.5, 0.0, 1.5]" + + +def test_legendre_3(): + """Test the 3rd Legendre polynomial.""" + assert legendre(3) == [0.0, -1.5, 0.0, 2.5], "The 3rd Legendre polynomial should be [0.0, -1.5, 0.0, 2.5]" + + +def test_legendre_4(): + """Test the 4th Legendre polynomial.""" + assert legendre(4) == pytest.approx([0.375, 0.0, -3.75, 0.0, 4.375]) + "The 4th Legendre polynomial should be [0.375, 0.0, -3.75, 0.0, 4.375]" + + +if __name__ == '__main__': + pytest.main()