# Legendre Polynomials in VBA

#### wellinth

##### Board Regular
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

### Excel Facts

Do you hate GETPIVOTDATA?
Prevent GETPIVOTDATA. Select inside a PivotTable. In the Analyze tab of the ribbon, open the dropown next to Options and turn it off

Replies
3
Views
94
Replies
4
Views
663
Replies
21
Views
664
Replies
74
Views
827
Replies
0
Views
74

1,195,989
Messages
6,012,718
Members
441,722
Latest member
tpaman1975

### We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.

### Which adblocker are you using?

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

### Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

### Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back