Skip to content

Support round with RoundFromZero #41182

@jessymilare

Description

@jessymilare

Currently, RoundFromZero is only supported for rounding BigFloats. I believe there is no reason for that, since a custom and simple round method for RoundFromZero has a performance similar to RoundNearestTiesUp.

function Base.round(x::AbstractFloat, ::typeof(RoundFromZero))
    round(x, ifelse(signbit(x), RoundDown, RoundUp))
end

When compiled with -O3:

julia> using BenchmarkTools

julia> v = rand(Float64, 10000) .* 200;

julia> w = similar(v);

julia> @benchmark w .= round.(v, Ref(RoundFromZero))
BenchmarkTools.Trial: 
  memory estimate:  72 bytes
  allocs estimate:  3
  --------------
  minimum time:     2.539 μs (0.00% GC)
  median time:      2.595 μs (0.00% GC)
  mean time:        2.626 μs (0.00% GC)
  maximum time:     9.616 μs (0.00% GC)
  --------------
  samples:          10000
  evals/sample:     9

julia> @benchmark w .= round.(v, Ref(RoundNearestTiesUp))
BenchmarkTools.Trial: 
  memory estimate:  72 bytes
  allocs estimate:  3
  --------------
  minimum time:     2.616 μs (0.00% GC)
  median time:      2.680 μs (0.00% GC)
  mean time:        2.713 μs (0.00% GC)
  maximum time:     6.895 μs (0.00% GC)
  --------------
  samples:          10000
  evals/sample:     9

julia> @benchmark w .= round.(v, Ref(RoundToZero))
BenchmarkTools.Trial: 
  memory estimate:  72 bytes
  allocs estimate:  3
  --------------
  minimum time:     2.069 μs (0.00% GC)
  median time:      2.103 μs (0.00% GC)
  mean time:        2.147 μs (0.00% GC)
  maximum time:     8.699 μs (0.00% GC)
  --------------
  samples:          10000
  evals/sample:     9

Related: #34519

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureIndicates new feature / enhancement requests

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions