Skip to content

Commit

Permalink
ndarray: type convertion of _div_scalar (apache#357)
Browse files Browse the repository at this point in the history
Ref: apache#353

- and handle the case of integer NDArray divided by zero
  • Loading branch information
iblislin authored and pluskid committed Dec 15, 2017
1 parent a941f3a commit 8135a63
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/ndarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -669,13 +669,21 @@ Matrix (2D NDArray) multiplication.
Elementwise divide a scalar or an `NDArray` of the same shape from `dst`. Inplace updating.
"""
function div_from!(dst::NDArray{T}, arg::NDArrayOrReal) where {T}
function div_from!(dst::NDArray, arg::NDArrayOrReal)
@assert dst.writable
if isa(arg, Real)
_div_scalar(dst, scalar = convert(T, arg), out = dst)
_div_scalar(dst, scalar = arg, out = dst)
else
_div(dst, arg, out = dst)
end
dst
end

function div_from!(dst::NDArray{T}, arg::Real) where {T<:Integer}
@assert dst.writable
@assert(round(T, arg) != zero(T), "Integer divided by zero")
_div_scalar(dst, scalar = arg, out = dst)
dst
end

"""
Expand Down
13 changes: 13 additions & 0 deletions test/unittest/ndarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,19 @@ function test_div()
t6, a6 = rand_tensors(Float16, dims)
scalar_large = 1e4
@test t6 ./ scalar_large copy(a6 ./ scalar_large)

info("NDArray::div::scalar::type convert")
let x = mx.NDArray([1, 2, 3])
y = x ./ 1.1
@test eltype(y) == Int
@test copy(y) == [1, 2, 3]

y = x ./ 2
@test eltype(y) == Int # this differs from julia
@test copy(y) == [0, 1, 1]

@test_throws AssertionError x ./ 0.5
end
end


Expand Down

0 comments on commit 8135a63

Please sign in to comment.