Skip to content

Instantly share code, notes, and snippets.

@charmby
Forked from samrat/trapezium.py
Created March 18, 2018 15:43
Show Gist options
  • Save charmby/a1751212f1eccbe343ba88b57d102165 to your computer and use it in GitHub Desktop.
Save charmby/a1751212f1eccbe343ba88b57d102165 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