Skip to content

Commit 5ee27b6

Browse files
i2000sdextorious
authored andcommitted
Correct the TrapezoidalEven() method and optimize the performance a little bit. (#8)
* Make integrations work for complex numbers as well. * Correct the formula of the TrapezoidalEven method. * Optimize the performance by reducing some unnecessary operations.
1 parent d999d21 commit 5ee27b6

File tree

2 files changed

+7
-4
lines changed

2 files changed

+7
-4
lines changed

src/NumericalIntegration.jl

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ end
2828

2929
function integrate{X<:Number, Y<:Number}(x::AbstractVector{X}, y::AbstractVector{Y}, ::TrapezoidalEven)
3030
@assert length(x) == length(y) "x and y vectors must be of the same length!"
31-
return 0.5 * (x[end] - x[1]) / (length(y) - 1) * (y[1] + y[end] + sum(y[2:end-1]))
31+
return (x[2] - x[1]) * (0.5 * (y[1] + y[end]) + sum(y[2:end-1]))
3232
end
3333

3434
function integrate{X<:Number, Y<:Number}(x::AbstractVector{X}, y::AbstractVector{Y}, ::TrapezoidalFast)
@@ -45,7 +45,7 @@ function integrate{X<:Number, Y<:Number}(x::AbstractVector{X}, y::AbstractVector
4545
@fastmath @simd for i in 2 : N
4646
@inbounds retval += y[i]
4747
end
48-
@inbounds return (x[end] - x[1]) / N * (retval + 0.5*y[1] + 0.5*y[end])
48+
@inbounds return (x[2] - x[1]) * (retval + 0.5*y[1] + 0.5*y[end])
4949
end
5050

5151
function integrate{X<:Number, Y<:Number}(x::AbstractVector{X}, y::AbstractVector{Y}, ::SimpsonEven)
@@ -54,7 +54,7 @@ function integrate{X<:Number, Y<:Number}(x::AbstractVector{X}, y::AbstractVector
5454
for i in 5 : length(y) - 1
5555
retval += y[i]
5656
end
57-
return (x[end] - x[1]) / (length(y) - 1) * retval
57+
return (x[2] - x[1]) * retval
5858
end
5959

6060
function integrate{X<:Number, Y<:Number}(x::AbstractVector{X}, y::AbstractVector{Y}, ::SimpsonEvenFast)
@@ -64,7 +64,7 @@ function integrate{X<:Number, Y<:Number}(x::AbstractVector{X}, y::AbstractVector
6464
@fastmath @inbounds for i in 5 : length(y)-1
6565
retval += y[i]
6666
end
67-
@inbounds return (x[end] - x[1]) / (length(y) - 1) * retval
67+
@inbounds return (x[2] - x[1]) * retval
6868
end
6969

7070
integrate{X<:Number, Y<:Number}(x::AbstractVector{X}, y::AbstractVector{Y}) = integrate(x, y, TrapezoidalFast())

test/runtests.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ using Base.Test
44
methods = [Trapezoidal(), TrapezoidalEven(), TrapezoidalFast(), TrapezoidalEvenFast(), SimpsonEven(), SimpsonEvenFast()]
55
x = collect(-π : π/1000 : π)
66
y = sin.(x)
7+
p = collect(0 : π/1000 : π)
8+
q = sin.(p)
79
for method in methods
810
println(string("Testing method: ", typeof(method)))
911
@test abs(integrate(x, y, method)) < 1e-4
12+
@test abs(integrate(p, q, method)-2.0) < 1e-4
1013
end

0 commit comments

Comments
 (0)