Skip to content

Commit

Permalink
fix JuliaLang#14111 dividing sparse vector by constant should give sp…
Browse files Browse the repository at this point in the history
…arse vector
  • Loading branch information
pgentili authored and tkelman committed Mar 28, 2016
1 parent 16cb001 commit 9e040f2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
9 changes: 9 additions & 0 deletions base/sparse/sparsevector.jl
Expand Up @@ -1250,6 +1250,15 @@ scale!(a::Complex, x::AbstractSparseVector) = scale!(nonzeros(x), a)
.*(a::Number, x::AbstractSparseVector) = SparseVector(length(x), copy(nonzeroinds(x)), a * nonzeros(x))
./(x::AbstractSparseVector, a::Number) = SparseVector(length(x), copy(nonzeroinds(x)), nonzeros(x) / a)

function /(x::AbstractSparseVector, a::Number)
if a == 0 || isnan(a)
throw(ArgumentError("Cannot divide sparse vector by provided argument"))
end
SparseVector(length(x), copy(x.nzind), x.nzval/a)
end

./(x::AbstractSparseVector, a::Number) = /(x,a)


# dot

Expand Down
22 changes: 22 additions & 0 deletions test/sparsedir/sparsevector.jl
Expand Up @@ -923,3 +923,25 @@ x = sparsevec(1:7, [3., 2., -1., 1., -2., -3., 3.], 15)
@test collect(sort(x, by=abs)) == sort(collect(x), by=abs)
@test collect(sort(x, by=sign)) == sort(collect(x), by=sign)
@test collect(sort(x, by=inv)) == sort(collect(x), by=inv)

# Issue 14111
# test vector with no zeros
s14111 = sparsevec([1., 2.5, -3., 8., -4])
a14111 = sparsevec([0.4, 1., -1.2, 3.2, -1.6])
@test exact_equal(s14111/2.5, a14111)
@test exact_equal(s14111./2.5, a14111)
# test vector with all zeros
s14111 = sparsevec(Int64[], Float64[], 10)
a14111 = sparsevec(Int64[], Float64[], 10)
@test exact_equal(s14111/5., a14111)
@test exact_equal(s14111./5., a14111)
# test vector with both zero and nonzero
s14111 = sparsevec([7., 0., -6., 3., 0., 2])
a14111 = sparsevec([1, 3, 4, 6], [2.8, -2.4, 1.2, 0.8], 6)
@test exact_equal(s14111/2.5, a14111)
@test exact_equal(s14111./2.5, a14111)
# test for division by illegal arguments
@test_throws ArgumentError s14111/0.
@test_throws ArgumentError s14111./0.
@test_throws ArgumentError s14111/NaN
@test_throws ArgumentError s14111./NaN

0 comments on commit 9e040f2

Please sign in to comment.