from math import sin, pi def Simpson(f, a, b, n): if a > b: print 'Incorrect bounds' return None if n%2 != 0: # also an 'if' because both tests are NOT # mutually exclusive print 'Invalid choice of n' return None else: h = (b - a)/float(n) # need to cast 'n' as float in order to avoid # integer division sum1 = 0 for i in range(1, n/2 + 1): sum1 += f(a + (2*i - 1)*h) sum1 *= 4 sum2 = 0 for i in range(1, n/2): # range must be ints: range() integer #end argument expected, got float. sum2 += f(a + 2*i*h) sum2 *= 2 approx = (b - a)/(3.0*n)*(f(a) + f(b) + sum1 + sum2) return approx ''' print 1.5*Simpson(sin(x)**3, 0, pi) NOT VALID B/C WE NEED TO DEFINE SIN(X)**3 AS IT'S OWN FUNCTION ''' def f(x): return 1.5*sin(x)**3 print "Simpson approximation of 1.5*sin(x)**3:" for n in 2,6,12,100,500: print 'For n=%g: approx=%f, error~%E' % \ (n, Simpson(f, 0, pi, n), 2 - Simpson(f, 0, pi, n)) ''' Sample run: Simpson approximation of f(x) = 1.5*sin(x)**3: For n=2: approx=3.141593, error~-1.141593E+00 For n=6: approx=1.989172, error~1.082830E-02 For n=12: approx=1.999489, error~5.107670E-04 For n=100: approx=2.000000, error~9.752365E-08 For n=500: approx=2.000000, error~1.558627E-10 ''' '''need to use polynomial of degree <=2 to verify Simpson a good candidate is g(x) = 3x**2, which will be exactly 1 with bounds [0,1]''' def g(x): return (3*x**2) print print "Simpson approximation of g(x) = 3*x**2:" for n in 2,6,12,100,500: print 'For n=%g: approx=%f, error~%E' % \ (n, Simpson(g, 0, 1, n), 1 - Simpson(g, 0, 1, n)) ''' Sample run: Simpson approximation of g(x) = 3*x**2: For n=2: approx=1.000000, error~0.000000E+00 For n=6: approx=1.000000, error~0.000000E+00 For n=12: approx=1.000000, error~2.220446E-16 For n=100: approx=1.000000, error~0.000000E+00 For n=500: approx=1.000000, error~3.330669E-16 '''
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question