Performing Numeric Integration

Introduction

Numeric integration is a method of approximating the definite integral of a function using numerical methods. It is often used when the antiderivative of a function cannot be determined analytically. Numeric integration has applications in various industries such as engineering, finance, physics, and computer science.

In engineering, it is used to approximate solutions to differential equations, finance to calculate the value of complex financial instruments, physics to calculate the motion of particles, and in computer science to simulate complex systems. Numeric integration is an important tool in many areas of science and engineering and is used to model a wide range of phenomena.

The following Python code creates functions for 5 different methods of numerical integration and derivatives using a data set. It also includes instructions on how to find the first and second derivatives.

Methods

Trapezoidal Rule:

def trapezoidal_rule(f, a, b, n):
    h = (b-a)/n
    sum = 0.5*f(a) + 0.5*f(b)
    for i in range(1, n):
        sum += f(a + i*h)
    return h*sum

Simpson’s Rule:

def simpson_rule(f, a, b, n):
    h = (b-a)/n
    sum = f(a) + f(b)
    for i in range(1, n, 2):
        sum += 4*f(a + i*h)
    for i in range(2, n-1, 2):
        sum += 2*f(a + i*h)
    return (h/3)*sum

Midpoint Rule:

def midpoint_rule(f, a, b, n):
    h = (b-a)/n
    sum = 0
    for i in range(n):
        x = a + h/2 + i*h
        sum += f(x)
    return h*sum

Left-hand Rule:

def left_hand_rule(f, a, b, n):
    h = (b-a)/n
    sum = 0
    for i in range(n):
        x = a + i*h
        sum += f(x)
    return h*sum

Right-hand Rule:

def right_hand_rule(f, a, b, n):
    h = (b-a)/n
    sum = 0
    for i in range(1, n+1):
        x = a + i*h
        sum += f(x)
    return h*sum

Derivatives

First Derivative:

def first_derivative(f, x, h):
    return (f(x+h) - f(x-h))/(2*h)

Second Derivative:

def second_derivative(f, x, h):
    return (f(x+h) - 2*f(x) + f(x-h))/(h**2)

In these functions, f is the function to be integrated or differentiated, a and b are the limits of integration, n is the number of subintervals, x is the point at which the derivative is to be evaluated, and h is the step size.