Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define new dot method for abstract vectors #22392

Merged
merged 5 commits into from
Jul 18, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions base/linalg/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,8 @@ dot(x::Number, y::Number) = vecdot(x, y)
dot(x, y)
⋅(x,y)

Compute the dot product. For complex vectors, the first vector is conjugated.
Compute the dot product between two vectors. For complex vectors, the first vector is conjugated.
When the vectors have equal lengths, calling `dot` is semantically equivalent to `sum(vx'vy for (vx,vy) in zip(x, y))`.

# Example

Expand All @@ -690,7 +691,29 @@ julia> dot([im; im], [1; 1])
0 - 2im
```
"""
dot(x::AbstractVector, y::AbstractVector) = vecdot(x, y)
function dot(x::AbstractVector, y::AbstractVector)
if length(x) != length(y)
throw(DimensionMismatch("dot product arguments have lengths $(length(x)) and $(length(y))"))
end
ix = start(x)
if done(x, ix)
# we only need to check the first vector, since equal lengths have been asserted
return zero(eltype(x))'zero(eltype(y))
end
@inbounds (vx, ix) = next(x, ix)
@inbounds (vy, iy) = next(y, start(y))
s = vx'vy
while !done(x, ix)
@inbounds (vx, ix) = next(x, ix)
@inbounds (vy, iy) = next(y, iy)
s += vx'vy
end
return s
end

# Call optimized BLAS methods for vectors of numbers
dot(x::AbstractVector{<:Number}, y::AbstractVector{<:Number}) = vecdot(x, y)


###########################################################################################

Expand Down
3 changes: 3 additions & 0 deletions test/linalg/matmul.jl
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,9 @@ end
@test dot(x, 1:2,y, 1:2) == convert(elty, 12.5)
@test x.'*y == convert(elty, 29.0)
@test_throws MethodError dot(rand(elty, 2, 2), randn(elty, 2, 2))
X = convert(Vector{Matrix{elty}},[reshape(1:4, 2, 2), ones(2, 2)])
res = convert(Matrix{elty}, [7.0 13.0; 13.0 27.0])
@test dot(X, X) == res
end

vecdot_(x,y) = invoke(vecdot, Tuple{Any,Any}, x,y) # generic vecdot
Expand Down