Dear all,
Does anyone have some (relatively) simple code for calculating the Simpson's Rule for integration?
Many thanks in advance.
Regards,
John
Dear all,
Does anyone have some (relatively) simple code for calculating the Simpson's Rule for integration?
Many thanks in advance.
Regards,
John
Here's another option.
There are two functions. SimpsonInt is the integrator, and it can be used as a worksheet function. Func is the function to be integrated. What's there now is arbitrary; change it to whatever you need. To test with the existing function, try
=SimpsonInt(0, PI()/2, n) for several values of n (the correct answer is 1)
Holler back if you need help.
![]()
Function SimpsonInt(a As Double, b As Double, ByVal n As Long) As Double ' Returns the integral of Func (below) from a to b _ using Composite Simpson's Rule over n intervals Dim i As Double ' index Dim dH As Double ' step size Dim dOdd As Double ' sum of Func(i), i = 1, 3, 5, 7, ... n-1, i.e., n/2 values Dim dEvn As Double ' sum of Func(i), i = 2, 4, 6, ... n-2 i.e., n/2 - 1 values ' 1 + (n/2) + (n/2 - 1) + 1 = n+1 function evaluations If n < 1 Then Exit Function If n And 1 Then n = n + 1 ' n must be even dH = (b - a) / n For i = 1 To n - 1 Step 2 dOdd = dOdd + Func(a + i * dH) Next For i = 2 To n - 2 Step 2 dEvn = dEvn + Func(a + i * dH) Next SimpsonInt = (Func(a) + 4# * dOdd + 2# * dEvn + Func(b)) * dH / 3# ' weighted sum End Function Function Func(x As Double) As Double ' replace this function with the function to be integrated Func = Sin(x) End Function
Last edited by shg; 06-15-2008 at 05:45 PM.
Sorry for bumping, but I really have to ask.
Can you please tell me what's the hashtags for after the numerical values (4# and 2#)? Thanks.
Type declaration character for a Double.
Entia non sunt multiplicanda sine necessitate
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks