I wrote a worksheet function in VBA to calculate the nth Legendre polynomial for a given value of x. The code is shown below. I'll be glad to answer any questions about it. I can also send anyone an Excel file that uses this function. Hope this helps.
Regards,
- Tom
Public Function Legendre(n As Integer, x As Double) As Double
'Computes the nth Legendre polynomial given x
Dim Pn As Double, Pn_1 As Double, Pn_2 As Double
Dim j As Integer
If n < 0 Then
MsgBox "n must be >= 0. Error"
Legendre = 0
Exit Function
End If
'P0 is 1 and P1 is x.
If n = 0 Then
Pn = 1
ElseIf n = 1 Then
Pn = x
Else 'n >= 2 so calculate Legendre polynomial iteratively
Pn_1 = 1
Pn = x
For j = 2 To n
Pn_2 = Pn_1
Pn_1 = Pn
Pn = (((2 * j - 1) * x * Pn_1) - ((j - 1) * Pn_2)) / j
Next j
End If
Legendre = Pn
End Function
Regards,
- Tom
Public Function Legendre(n As Integer, x As Double) As Double
'Computes the nth Legendre polynomial given x
Dim Pn As Double, Pn_1 As Double, Pn_2 As Double
Dim j As Integer
If n < 0 Then
MsgBox "n must be >= 0. Error"
Legendre = 0
Exit Function
End If
'P0 is 1 and P1 is x.
If n = 0 Then
Pn = 1
ElseIf n = 1 Then
Pn = x
Else 'n >= 2 so calculate Legendre polynomial iteratively
Pn_1 = 1
Pn = x
For j = 2 To n
Pn_2 = Pn_1
Pn_1 = Pn
Pn = (((2 * j - 1) * x * Pn_1) - ((j - 1) * Pn_2)) / j
Next j
End If
Legendre = Pn
End Function