[swift-evolution] [Proposal] Add floor() and ceiling() functions to FloatingPoint

Stephen Canon scanon at apple.com
Wed Jun 29 12:00:52 CDT 2016


> On Jun 29, 2016, at 12:46 PM, Matthew Johnson <matthew at anandabits.com> wrote:
> 
> +1 to adding robust rounding to he standard library.
> 
> I’m curious why we have both `up` and `down`, but only have `towardZero` without `awayFromZero`.
> 
> I’m also curious what the use case is for `toNearestOrEven` and why you don’t include `toNearestOrOdd`.
> 
> I think the name of `toNearestOrGreatest` could use improvement.  The name doesn’t indicate greatest magnitude and could easily be confused with some `toNearestOrUp` (rounding towards positive infinity).  Maybe you should call it `toNearestOrAwayFromZero` (building on the convention implied by `towardZero`).  This also raises the question of why we don’t have other similar rules such as `toNearestOrDown` and `toNearestOrTowardZero`.
> 
> Maybe there are good reasons for covering a subset of the possible space of rounding rules but not all of it.  If there are you should provide rationale in the proposal.  If there aren’t, maybe you should consider including the additional options.  


The rounding rules in the proposal are precisely the rounding rules required by IEEE 754.  Not coincidentally, these are also the rounding rules that have fast hardware support for concrete types on common architectures, and the rounding rules that software expects to be able to use.

Of your suggestions for symmetry, I’ve only ever seen `awayFromZero` used (e.g. I’ve never seen anyone use `toNearestOrOdd`).  If we did want to extend the set of IEEE 754 rounding rules, I would add the following two rules:

/// The result is the closest representable value whose magnitude is greater than or equal to that of the source.
//  Rationale: it’s actually used, though not as frequently as the operations in the proposal.
case awayFromZero

/// If the source is not exactly representable, the result is the closest odd number.
//  Rationale: although this is mostly useless for rounding-to-integer, it’s an extremely useful rounding rule to have for *other* floating-point operations, so if we’re going to extend the set, it makes sense to add it.
case toOdd

I have never seen a use case that would require extending the set any further than that.

The thing that would actually be extremely useful is support for dithered or stochastic rounding, but that’s a can of API design worms that’s out of scope for Swift 3; you need to be able to describe not just the rule, but also a noise source and shape / spectrum.

– Steve
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160629/c49ddc37/attachment.html>


More information about the swift-evolution mailing list