Skip to content

Instantly share code, notes, and snippets.

@samrat
Created August 27, 2011 07:40
Show Gist options
  • Save samrat/1175111 to your computer and use it in GitHub Desktop.
Save samrat/1175111 to your computer and use it in GitHub Desktop.
Definite integration using the trapezium rule
from __future__ import division
def trapezium(f, n, a, b):
'''
f- function [f(x)]
n- number of trapeziums
a- lower limit
b- upper limit
Returns definite integral of f(x) from range a to b
'''
h = (b-a)/n
area = 0.5*h
sum_y = f(a)+f(b)
part_sum = 0
for i in xrange(1, n):
part_sum += f(a+h*i)
sum_y += 2*part_sum
area *= sum_y
return area
def f(x):
return x ** 2
print trapezium(f, 100000, 0, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment