Created
November 24, 2014 23:58
-
-
Save cbcunc/5c564fecde0519c1e814 to your computer and use it in GitHub Desktop.
Estimate the area under the curve using Riemann–Darboux's Method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"metadata": { | |
"name": "", | |
"signature": "sha256:25966a5667f39011dd93d3d337860e302b8c68ac708ef3bbe73df838f8cc544f" | |
}, | |
"nbformat": 3, | |
"nbformat_minor": 0, | |
"worksheets": [ | |
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"from math import pi, sin\n", | |
"from numpy import linspace\n", | |
"\n", | |
"def integrate(f, interval, samples):\n", | |
" \"\"\"Compute a definite integral of a function over\n", | |
" an interval using Riemann\u2013Darboux's Method.\"\"\"\n", | |
" delta_x = (interval[1] - interval[0]) / samples\n", | |
" return sum([f(x) * delta_x for x in linspace(interval[0] + delta_x, interval[1], num=samples)])" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [], | |
"prompt_number": 20 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"# Estimate the area under the curve using progressively smaller delta x.\n", | |
"interval = (0, pi)\n", | |
"for samples in (50, 100, 1000, 10000):\n", | |
" print \"The integral of sin(x) over 0 to pi is %f when using %u samples.\" % \\\n", | |
" (integrate(sin, interval, samples), samples)" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"The integral of sin(x) over 0 to pi is 1.999342 when using 50 samples.\n", | |
"The integral of sin(x) over 0 to pi is 1.999836 when using 100 samples.\n", | |
"The integral of sin(x) over 0 to pi is 1.999998 when using 1000 samples.\n", | |
"The integral of sin(x) over 0 to pi is 2.000000 when using 10000 samples.\n" | |
] | |
} | |
], | |
"prompt_number": 21 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [], | |
"prompt_number": 21 | |
} | |
], | |
"metadata": {} | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment