Last active
May 15, 2016 13:34
-
-
Save AFAgarap/9e55781053d7b42c475cfad8e0b02431 to your computer and use it in GitHub Desktop.
Trapezoidal rule, a technique for approximating a definite integral
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
# 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