From a85cc64500b07739672c7d1fa8832b17f18a1bf1 Mon Sep 17 00:00:00 2001 From: Paolo Gentili Date: Sat, 6 Feb 2016 17:26:10 -0500 Subject: [PATCH] fix #14111 dividing sparse vector by constant should give sparse vector --- base/sparse.jl | 2 +- base/sparse/sparsevector.jl | 9 +++++++++ test/sparsedir/sparsevector.jl | 22 ++++++++++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/base/sparse.jl b/base/sparse.jl index e8ae4bf35b61b..edc97f188e829 100644 --- a/base/sparse.jl +++ b/base/sparse.jl @@ -6,7 +6,7 @@ using Base: Func, AddFun, OrFun, ConjFun, IdFun using Base.Sort: Forward using Base.LinAlg: AbstractTriangular, PosDefException -import Base: +, -, *, \, &, |, $, .+, .-, .*, ./, .\, .^, .<, .!=, == +import Base: +, -, *, /, \, &, |, $, .+, .-, .*, ./, .\, .^, .<, .!=, == import Base: A_mul_B!, Ac_mul_B, Ac_mul_B!, At_mul_B, At_mul_B!, At_ldiv_B, Ac_ldiv_B, A_ldiv_B! import Base.LinAlg: At_ldiv_B!, Ac_ldiv_B! diff --git a/base/sparse/sparsevector.jl b/base/sparse/sparsevector.jl index 83526e6bc097b..4fc552978a653 100644 --- a/base/sparse/sparsevector.jl +++ b/base/sparse/sparsevector.jl @@ -1201,6 +1201,15 @@ scale(a::Complex, x::AbstractSparseVector) = scale(x, a) .*(x::AbstractSparseVector, a::Number) = scale(x, a) .*(a::Number, x::AbstractSparseVector) = scale(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 diff --git a/test/sparsedir/sparsevector.jl b/test/sparsedir/sparsevector.jl index 069cf5c67eb45..07c4f504365aa 100644 --- a/test/sparsedir/sparsevector.jl +++ b/test/sparsedir/sparsevector.jl @@ -838,3 +838,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