Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 98c64d5

Browse files
committedDec 3, 2024·
Implemented Legendre polynomial computation algorithm
Added an algorithm that calculates the coefficients of the Legendre polynomial of degree n using the recurrence relation.
1 parent 1d1eda9 commit 98c64d5

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
 

‎maths/polynomials/legendre.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
from numpy.polynomial import Polynomial
2+
from math import factorial
3+
import pytest
4+
5+
6+
def legendre(n: int) -> list[float]:
7+
"""
8+
Compute the coefficients of the nth Legendre polynomial.
9+
10+
The Legendre polynomials are solutions to Legendre's differential equation
11+
and are widely used in physics and engineering.
12+
13+
Parameters:
14+
n (int): The order of the Legendre polynomial.
15+
16+
Returns:
17+
list[float]: Coefficients of the polynomial in ascending order of powers.
18+
"""
19+
p = (1 / (factorial(n) * (2 ** n))) * (Polynomial([-1, 0, 1]) ** n)
20+
return p.deriv(n).coef.tolist()
21+
22+
23+
def jsp():
24+
print(legendre(1))
25+
print(legendre(2))
26+
print(legendre(3))
27+
print(legendre(4))
28+
29+
30+
jsp()
31+
32+
33+
def test_legendre_0():
34+
"""Test the 0th Legendre polynomial."""
35+
assert legendre(0) == [1.0], "The 0th Legendre polynomial should be [1.0]"
36+
37+
38+
def test_legendre_1():
39+
"""Test the 1st Legendre polynomial."""
40+
assert legendre(1) == [0.0, 1.0], "The 1st Legendre polynomial should be [0.0, 1.0]"
41+
42+
43+
def test_legendre_2():
44+
"""Test the 2nd Legendre polynomial."""
45+
assert legendre(2) == [-0.5, 0.0, 1.5], "The 2nd Legendre polynomial should be [-0.5, 0.0, 1.5]"
46+
47+
48+
def test_legendre_3():
49+
"""Test the 3rd Legendre polynomial."""
50+
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]"
51+
52+
53+
def test_legendre_4():
54+
"""Test the 4th Legendre polynomial."""
55+
assert legendre(4) == pytest.approx([0.375, 0.0, -3.75, 0.0, 4.375])
56+
"The 4th Legendre polynomial should be [0.375, 0.0, -3.75, 0.0, 4.375]"
57+
58+
59+
if __name__ == '__main__':
60+
pytest.main()

0 commit comments

Comments
 (0)
Please sign in to comment.