Or you can use the non-vectorized version and save the overhead of the
temporary arrays being created by the addition and multiplication steps.

function trapz{T<:Real}(x::Vector{T}, y::Vector{T})
    local len = length(y)
    if (len != length(x))
        error("Vectors must be of same length")
    end
    r = 0.0
    for i in 2:len
        r += (x[i] - x[i-1]) * (y[i] + y[i-1])
    end
    r/2.0
end

BTW, another possibility is to use a spline interpolation on the original
data and integrate the spline evaluation  with quadgk().  (Ideally,
integrations can be incorporated into a spline interface.) This could be
useful depending on the functional shape between the grid points.

Cameron


On Wed, Apr 23, 2014 at 7:52 AM, Tomas Lycken <tomas.lyc...@gmail.com>wrote:

> The trapezoidal rule (http://en.wikipedia.org/wiki/Trapezoidal_rule)
> would probably be almost trivial to implement.
>
> function trapz{T<:Real}(x::Vector{T}, y::Vector{T})
>    if (length(y) != length(x))
>        error("Vectors must be of same length")
>    end
>    sum( (x[2:end] .- x[1:end-1]).*(y[2:end].+y[1:end-1]) ) / 2
> end
>
> x = [0:0.01:pi]
> y = sin(x)
>
> trapz(x,y) # 1.9999820650436642
>
> This, of course, only currently works on vectors of real numbers, but it's
> easy to extend it if you want.
>
> And there might be more accurate methods as well, of course (see e.g.
> http://en.wikipedia.org/wiki/Simpson%27s_rule) but this one's often "good
> enough".
>
> // T
>
> On Wednesday, April 23, 2014 8:43:48 AM UTC+2, Evgeny Shevchenko wrote:
>
>> Hi, John.
>> No, I didn't. I didn't find it and it seems to be not what i need:
>>
>> "no method quadgk(Array{Float64,1}, Array{Float64,1})"
>>
>> quadgk(f,a,b,...) expects a function as its first argument but I mean the
>> case when y = f(x), but i don't have f, e.g. obtained experimental data, so
>> x and y are 1-D arrays of floats.
>>
>>
>> On Tue, Apr 22, 2014 at 7:49 PM, John Myles White 
>> <johnmyl...@gmail.com>wrote:
>>
>>> Have you tried the quadgk function?
>>>
>>>  -- John
>>>
>>> On Apr 22, 2014, at 7:32 AM, Evgeny Shevchenko <eu...@ya.ru> wrote:
>>>
>>> Hi
>>>
>>> Is there a package for numeric integration of obtained arrays, say x and
>>> y? Couldn't find one, the led me to use @pyimport and numpy.trapz.
>>>
>>> --
>>> pupoque@IRC
>>>
>>>
>>>
>>

Reply via email to