Skip to content

Commit a26a0b8

Browse files
committed
Merge pull request #11514 from JuliaLang/sjk/fix-round-digits
Fix round(::AbstractArray, digits::Int) etc.
2 parents d20debf + 848dfc5 commit a26a0b8

File tree

2 files changed

+22
-9
lines changed

2 files changed

+22
-9
lines changed

base/floatfuncs.jl

+12-9
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,15 @@ for f in (:trunc,:floor,:ceil,:round)
7777
function ($f){T}(::Type{T}, x::AbstractArray)
7878
reshape([ ($f)(T, x[i])::T for i in eachindex(x) ], size(x))
7979
end
80+
function ($f){R}(x::AbstractArray{R,1}, digits::Integer, base::Integer=10)
81+
[ ($f)(x[i], digits, base) for i = 1:length(x) ]
82+
end
83+
function ($f){R}(x::AbstractArray{R,2}, digits::Integer, base::Integer=10)
84+
[ ($f)(x[i,j], digits, base) for i = 1:size(x,1), j = 1:size(x,2) ]
85+
end
86+
function ($f)(x::AbstractArray, digits::Integer, base::Integer=10)
87+
reshape([ ($f)(x[i], digits, base) for i in eachindex(x) ], size(x))
88+
end
8089
end
8190
end
8291

@@ -135,7 +144,7 @@ end
135144

136145
for f in (:round, :ceil, :floor, :trunc)
137146
@eval begin
138-
function ($f)(x, digits::Integer, base::Integer=10)
147+
function ($f)(x::Real, digits::Integer, base::Integer=10)
139148
x = float(x)
140149
og = convert(eltype(x),base)^digits
141150
r = ($f)(x * og) / og
@@ -144,15 +153,9 @@ for f in (:round, :ceil, :floor, :trunc)
144153
if digits > 0
145154
return x
146155
elseif x > 0
147-
if ceil == $f
148-
return convert(eltype(x), Inf)
149-
end
150-
return zero(x)
156+
return $(:ceil == f ? :(convert(eltype(x), Inf)) : :(zero(x)))
151157
elseif x < 0
152-
if floor == $f
153-
return -convert(eltype(x), Inf)
154-
end
155-
return -zero(x)
158+
return $(:floor == f ? :(-convert(eltype(x), Inf)) : :(-zero(x)))
156159
else
157160
return x
158161
end

test/numbers.jl

+10
Original file line numberDiff line numberDiff line change
@@ -1860,6 +1860,16 @@ x = 0.0
18601860
@test approx_eq(round(pi,2,2), 3.25)
18611861
@test approx_eq(round(pi,3,2), 3.125)
18621862
@test approx_eq(round(pi,3,5), 3.144)
1863+
# vectorized trunc/round/floor/ceil with digits/base argument
1864+
a = rand(2, 2, 2)
1865+
for f in (trunc, round, floor, ceil)
1866+
@test f(a[:, 1, 1], 2) == map(x->f(x, 2), a[:, 1, 1])
1867+
@test f(a[:, :, 1], 2) == map(x->f(x, 2), a[:, :, 1])
1868+
@test f(a, 9, 2) == map(x->f(x, 9, 2), a)
1869+
@test f(a[:, 1, 1], 9, 2) == map(x->f(x, 9, 2), a[:, 1, 1])
1870+
@test f(a[:, :, 1], 9, 2) == map(x->f(x, 9, 2), a[:, :, 1])
1871+
@test f(a, 9, 2) == map(x->f(x, 9, 2), a)
1872+
end
18631873
# significant digits (would be nice to have a smart vectorized
18641874
# version of signif)
18651875
@test approx_eq(signif(123.456,1), 100.)

0 commit comments

Comments
 (0)