The Simpson’s Method

{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Simpson's Rule is a numerical method that approximates the value of a definite integral by using quadratic functions. This method is named after the English mathematician Thomas Simpson (1710−1761)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's check this method for the next function: $$f(x) = ({e^x / 2})*(cos(x)-sin(x))$$ with $\\varepsilon = 0.001$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math \n",
    "import numpy as np\n",
    "\n",
    "def simpsone(a, b, n, func):\n",
    "    h = float((b-a)/n)\n",
    "    s = (func(a) + func(b)) * 0.5\n",
    "    for i in np.arange(0, n-1):\n",
    "        xk = a + h*i\n",
    "        xk1 = a + h*(i-1)\n",
    "        s = s + func(xk) + 2*func((xk1+xk)/2)\n",
    "    x = a + h*n\n",
    "    x1 = a + h*(n-1)\n",
    "    s += 2 *func((x1 + x)/2)\n",
    "    return s*h/3.0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Some input data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Result:  -8.404153016168566\n"
     ]
    }
   ],
   "source": [
    "f = lambda x: (math.e**x / 2)*(math.cos(x)-math.sin(x))\n",
    "\n",
    "n = 10000  \n",
    "a = 2.0\n",
    "b = 3.0\n",
    "\n",
    "print(\"Result: \", simpsone(a, b, n, f))"
   ]
  }
 ],
 "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.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
About this Algorithm

Simpson's Rule is a numerical method that approximates the value of a definite integral by using quadratic functions. This method is named after the English mathematician Thomas Simpson (1710−1761).

Let's check this method for the next function: $$f(x) = ({e^x / 2})*(cos(x)-sin(x))$$ with $\varepsilon = 0.001$

import math 
import numpy as np

def simpsone(a, b, n, func):
    h = float((b-a)/n)
    s = (func(a) + func(b)) * 0.5
    for i in np.arange(0, n-1):
        xk = a + h*i
        xk1 = a + h*(i-1)
        s = s + func(xk) + 2*func((xk1+xk)/2)
    x = a + h*n
    x1 = a + h*(n-1)
    s += 2 *func((x1 + x)/2)
    return s*h/3.0

Some input data

f = lambda x: (math.e**x / 2)*(math.cos(x)-math.sin(x))

n = 10000  
a = 2.0
b = 3.0

print("Result: ", simpsone(a, b, n, f))
Result:  -8.404153016168566