Understood about the "if"; I often used this extra statement because of differences between Matlab and R. The function as is returns a floating point number also for integer input 'x', 'y'. But I am more worried about the case that one of the vectors is real, the other complex. Do I need two types T1 and T2 for defining different types for the input vectors?
On Thursday, April 24, 2014 10:36:29 PM UTC+2, Cameron McBride wrote: > > > On Thu, Apr 24, 2014 at 4:28 AM, Hans W Borchers > <[email protected]<javascript:> > > wrote: >> >> function trapz2{T<:Number}(x::Vector{T}, y::Vector{T}) >> local n = length(x) >> if (length(y) != n) >> error("Vectors 'x', 'y' must be of same length") >> end >> if n == 1; return 0.0; end >> r = 0.0 >> for i in 2:n >> r += (x[i] - x[i-1]) * (y[i] + y[i-1]) >> >> end >> r / 2.0 >> end >> >> > I'm not sure it's behavior we should "rely on", but the if branch for n == > 1 isn't necessary in this for loop, although perhaps it was included to aid > the comparison. A range of 2:1 is a zero-length iteration, so the loop will > not run even once. Try this: > > julia> [2:1] > 0-element Array{Int64,1} > > If we are being pedantic on types, then the result of the integral should > at least be a floating point. Granted, I am not sure of what the use case > for integer vector inputs would be, but I doubt *if* someone used them that > they'd want an integer result in return. (This would be similar to sqrt(), > for example.) > > Cameron >
