{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Trapezoid rule using scipy" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from scipy.integrate import trapz" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example\n", "$$\n", "f(x) = x, \\qquad x \\in [0,1]\n", "$$\n", "Exact integral is 0.5" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Integral = 0.5\n" ] } ], "source": [ "f = lambda x: x\n", "a,b,n = 0.0,1.0,10\n", "x = np.linspace(a,b,n)\n", "y = f(x)\n", "print(\"Integral = \", trapz(y,x))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example\n", "$$\n", "f(x) = x^2, \\qquad x \\in [0,1]\n", "$$\n", "Exact integral is $1/3$" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Integral = 0.33539094650205764\n" ] } ], "source": [ "f = lambda x: x**2\n", "a,b,n = 0.0,1.0,10\n", "x = np.linspace(a,b,n)\n", "y = f(x)\n", "print(\"Integral = \", trapz(y,x))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For uniformly space points we can just pass the spacing instead of $x$." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Integral = 0.33539094650205753\n" ] } ], "source": [ "h = (b-a)/(n-1)\n", "print(\"Integral = \", trapz(y,dx=h))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.6" } }, "nbformat": 4, "nbformat_minor": 2 }