Skip to content

Instantly share code, notes, and snippets.

@AFAgarap
Last active May 15, 2016 13:34
Show Gist options
  • Save AFAgarap/9e55781053d7b42c475cfad8e0b02431 to your computer and use it in GitHub Desktop.
Save AFAgarap/9e55781053d7b42c475cfad8e0b02431 to your computer and use it in GitHub Desktop.
Trapezoidal rule, a technique for approximating a definite integral
# Numerical Analysis
# Trapezoidal Method
# Author: A.F. Agarap
# Function = SUM(i = 1, n) h / 2 (f(x[1]) + f(x[n + 1]) + 2(f(x[2]) + f(x[3]) + ... + f(x[n])))
# f(x) = cos(x**2) * exp(x**3)
import math
import os
def main():
a = int(input("Enter value for a: "))
b = int(input("Enter value for b: "))
n = int(input("Enter value for n: "))
x = generate_set(a, b, n)
result = 0
for i in range(0, (n + 1)):
result += function(x[i]) if (i == 0 or i == n) else (2 * function(x[i]))
print(result * ((abs(a - b) / n) / 2))
def generate_set(a, b, n):
x = []
h = abs(a - b) / n
for i in range(n + 1):
x.append(a + (i * h))
return x
def function(x):
return math.cos(x**2) * math.exp(x**3)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment