|
1 | 1 | module NumericalIntegration
|
2 | 2 |
|
3 |
| -# package code goes here |
| 3 | +abstract IntegrationMethod |
| 4 | +immutable Trapezoidal <: IntegrationMethod end |
| 5 | +immutable TrapezoidalEven <: IntegrationMethod end |
| 6 | +immutable TrapezoidalFast <: IntegrationMethod end |
| 7 | +immutable TrapezoidalEvenFast <: IntegrationMethod end |
| 8 | +immutable SimpsonEven <: IntegrationMethod end # https://en.wikipedia.org/wiki/Simpson%27s_rule#Alternative_extended_Simpson.27s_rule |
4 | 9 |
|
5 |
| -end # module |
| 10 | +integrate{T<:AbstractFloat}(x::Vector{T}, y::Vector{T}, method::IntegrationMethod=Trapezoidal()) = integrate(x, y, method) |
| 11 | + |
| 12 | +function integrate{T<:AbstractFloat}(x::Vector{T}, y::Vector{T}, ::Trapezoidal) |
| 13 | + @assert length(x) == length(y) "x and y vectors must be of the same length!" |
| 14 | + retval = zero(eltype(x)) |
| 15 | + for i in 1 : length(y)-1 |
| 16 | + retval += (x[i+1] - x[i]) * (y[i] + y[i+1]) |
| 17 | + end |
| 18 | + return 0.5 * retval |
| 19 | +end |
| 20 | + |
| 21 | +function integrate{T<:AbstractFloat}(x::Vector{T}, y::Vector{T}, ::TrapezoidalEven) |
| 22 | + @assert length(x) == length(y) "x and y vectors must be of the same length!" |
| 23 | + return 0.5 * (x[end] - x[1]) / (length(y) - 1) * (y[1] + y[end] + sum(y[2:end-1])) |
| 24 | +end |
| 25 | + |
| 26 | +function integrate{T<:AbstractFloat}(x::Vector{T}, y::Vector{T}, ::TrapezoidalFast) |
| 27 | + retval = zero(eltype(x)) |
| 28 | + @fastmath @simd for i in 1 : length(y)-1 |
| 29 | + @inbounds retval += (x[i+1] - x[i]) * (y[i] + y[i+1]) |
| 30 | + end |
| 31 | + return 0.5 * retval |
| 32 | +end |
| 33 | + |
| 34 | +function integrate{T<:AbstractFloat}(x::Vector{T}, y::Vector{T}, ::TrapezoidalEvenFast) |
| 35 | + retval = zero(eltype(x)) |
| 36 | + N = length(y) - 1 |
| 37 | + @fastmath @simd for i in 2 : N |
| 38 | + @inbounds retval += y[i] |
| 39 | + end |
| 40 | + @inbounds return (x[end] - x[1]) / N * (retval + 0.5*y[1] + 0.5*y[end]) |
| 41 | +end |
| 42 | + |
| 43 | +function integrate{T<:AbstractFloat}(x::Vector{T}, y::Vector{T}, ::SimpsonEven) |
| 44 | + @assert length(x) == length(y) "x and y vectors must be of the same length!" |
| 45 | + retval = 17*y[1] + 59*y[2] + 43*y[3] + 49*y[4] + 49*y[end-3] + 43*y[end-2] + 59*y[end-1] + 17*y[end] |
| 46 | + retval /= 48 |
| 47 | + for i in 5 : length(y) - 1 |
| 48 | + retval += y[i] |
| 49 | + end |
| 50 | + return (x[end] - x[1]) / (length(y) - 1) * retval |
| 51 | +end |
| 52 | + |
| 53 | +export integrate |
| 54 | +export Trapezoidal, TrapezoidalEven, TrapezoidalFast, TrapezoidalEvenFast |
| 55 | +export SimpsonEven |
| 56 | + |
| 57 | +end |
0 commit comments