code for Simpson’s rule

Python code for Simpson’s rule

from math import *
def f(x):
  #function to integrate
  return sin(x)

def simpson_rule(a,b):
  #Approximation by Simpson's ruleMathworldPlanetmath
  return h*(f(a)+4.0*f(c)+f(b))/3.0

# Calculates integral of f(x) from 0 to 1
print simpson_rule(0,1)

Integrating sinx from 0 to 1 with the previous code gives 0.45986218971 whereas the true value is 1-cos1=0.459697694131860282599063392557.

Title code for Simpson’s rule
Canonical name CodeForSimpsonsRule
Date of creation 2013-03-22 14:50:52
Last modified on 2013-03-22 14:50:52
Owner drini (3)
Last modified by drini (3)
Numerical id 7
Author drini (3)
Entry type AlgorithmMathworldPlanetmath
Classification msc 65D32
Related topic NewtonAndCotesFormulas