Trapezoid Integration

"""
    trapezoid_integration(f::Function, a::Real, b::Real, n::Int)

The trapezoidal rule works by approximating the region under the graph of the function f(x) as a trapezoid and calculating its area.

# Arguments
- `f`: the function to integrate. (at the momment only single variable is suported)
- `a`: Start of the integration limit.
- `b`: End of the integration limit.
- `n`: Number of points to sample. (as n increase, error decrease)

# Examples/Test
```julia
julia> trapezoid_integration(x -> 4 / (1 + x^2), 0, 1, 100_000)
3.1415926535731526
julia> trapezoid_integration(x -> 4 / (1 + x^2), 0, 1, 100_000) β‰ˆ pi
true
```
# References:
-https://personal.math.ubc.ca/~pwalls/math-python/integration/trapezoid-rule/
-https://en.wikipedia.org/wiki/Trapezoidal_rule

# Contributed By:- [AugustoCL](https://github.com/AugustoCL)
"""
function trapezoid_integration(f::Function, a::Real, b::Real, n::Int)
    # width of the trapezoids
    Ξ”β‚“ = (b - a) / n

    # sum of the height of the trapezoids
    Ξ£ = 0.5 * f(a) + sum(f(i) for i in (a+Ξ”β‚“):Ξ”β‚“:(b-Ξ”β‚“)) + 0.5 * f(b)

    # approximate integral of f
    return Ξ”β‚“ * Ξ£
end
Algerlogo

Β© Alger 2022

About us

We are a group of programmers helping each other build new things, whether it be writing complex encryption programs, or simple ciphers. Our goal is to work together to document and model beautiful, helpful and interesting algorithms using code. We are an open-source community - anyone can contribute. We check each other's work, communicate and collaborate to solve problems. We strive to be welcoming, respectful, yet make sure that our code follows the latest programming guidelines.