The Algorithms logo
The Algorithms
关于捐赠

The Trapezium Method

H
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The trapezium rule is a way of estimating the area under a curve. We know that the area under a curve is given by integration, so the trapezium rule gives a method of estimating integrals."
   ]
  },
  {
   "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": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Result:  -22.12539445092147\n"
     ]
    }
   ],
   "source": [
    "import math \n",
    "import numpy as np\n",
    "\n",
    "n = 4 \n",
    "a = 2.\n",
    "b = 3.\n",
    "def f(x):\n",
    "    return  (math.e**x / 2)*(math.cos(x)-math.sin(x))\n",
    "\n",
    "def trapezoid(a,b,n):\n",
    "  z = (b-a)/n\n",
    "  i=a\n",
    "  s=0\n",
    "  while (i+z)<b:\n",
    "    s=s+f(i)\n",
    "    i=i+z \n",
    "  s=z*(f(a)+f(b))/2+s\n",
    "  print('Result: ',s)\n",
    "    \n",
    "trapezoid(a,b,n)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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
}
关于这个算法

The trapezium rule is a way of estimating the area under a curve. We know that the area under a curve is given by integration, so the trapezium rule gives a method of estimating integrals.

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

n = 4 
a = 2.
b = 3.
def f(x):
    return  (math.e**x / 2)*(math.cos(x)-math.sin(x))

def trapezoid(a,b,n):
  z = (b-a)/n
  i=a
  s=0
  while (i+z)&lt;b:
    s=s+f(i)
    i=i+z 
  s=z*(f(a)+f(b))/2+s
  print('Result: ',s)
    
trapezoid(a,b,n)
Result:  -22.12539445092147