Post Reply 
Simpson's Rule Implementation trick?
03-18-2016, 12:11 AM (This post was last modified: 03-21-2016 03:32 AM by Namir.)
Post: #1
Simpson's Rule Implementation trick?
I found C code in an article on the Internet that implements Simpson's rule using a single for loop. Here is the pseudo-code for the C code:

Code:

Simpson's Rule for Numerical Integration Ver 1
======================================

Given f(x) and limit [a, b} with n points

if n modulo 2 = 0 then n = n + 1
h = (b - a) / (n + 1)
sum = f(a) + f(b) + 4*f(a+h)

for i=2 to n step 2
  sum = sum + 2*f(a+i*h) + 4*f(a + (i+1)*h)
next
area = h/3*sum

Here is a version that I modified to avoid using a+i*h and a+(i+1)*h:

Code:

Simpson's Rule for Numerical Integration Ver 2
======================================

Given f(x) and limit [a, b} with n points

if n modulo 2 = 0 then n = n + 1
h = (b - a) / (n + 1)
x = a+h
sum = f(a) + f(b) + 4*f(x)

for i=2 to n step 2
  x = x + h
  sum = sum + 2*f(x)
  x = x + h
  sum = sum + 4*f(x)
next
area = h/3*sum

Consolidating the for loop to have a single update to sum:

Code:
Simpson's Rule for Numerical Integration Ver 3
==============================================

Given f(x) and limit [a, b} with n points

if n modulo 2 = 0 then n = n + 1
h = (b - a) / (n + 1)
x = a+h
sum = f(a) + f(b) + 4*f(x)
c = 2
for i=2 to n
  x = x + h
  sum = sum + c*f(x)
  c = 6 - c
next
area = h/3*sum

Enjoy!

Namir
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
Simpson's Rule Implementation trick? - Namir - 03-18-2016 12:11 AM



User(s) browsing this thread: 1 Guest(s)