Yes; if the vectors aren't of the same type, this method isn't applicable. 
(In other words, you need to have two type arguments in order to support 
one vector of ints and one vector of floating points). In this case, 
though, it's probably reasonable to expect only floating point arguments 
(of the same size), at least as long as they're real.

And as soon as you start working with complex analysis, I'm not entirely 
sure the trapezoidal rule is valid at all. It might just be because the 
article author was lazy, but the Wikipedia article only talks about 
integrals of real-valued functions of one (real, scalar) variable. If you 
need complex numbers for something more than curiosity about Julia's type 
system, you probably want another approach altogether...

// Tomas

On Friday, April 25, 2014 7:45:16 AM UTC+2, Hans W Borchers wrote:
>
> 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]>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
>>
>

Reply via email to