[issue2748] ceil(), floor() and round() broken in Decimal

Mark Dickinson report at bugs.python.org
Sun May 4 03:35:26 CEST 2008


Mark Dickinson <dickinsm at gmail.com> added the comment:

Here's a patch that implements __ceil__, __floor__ and __round__.  (It 
seems that just removing __ceil__, __floor__ and __round__ is not an 
option, as I just discovered when r62669 turned all the buildbots red.)

Points to note:

(1) Two-argument round has essentially the same semantics as quantize.  
To be precise, for a Decimal instance x and an int n,

round(x, n) 

is exactly interchangeable with 

x.quantize(Decimal('1E%s' % -n))

In particular, this means that round uses the rounding mode from the 
current context (which will usually, but not always, be 
ROUND_HALF_EVEN), and that an InvalidOperation exception will be raised 
(or NaN returned) if the rounded value has too many digits for the 
current context precision.

After thinking about it, it seemed better to make the two expressions 
above identical than to have subtle and potentially confusing 
differences between them.

(2) Decimal.__round__ takes two optional arguments, 'context' and 
'rounding', again with exactly the same semantics as the corresponding 
optional arguments for quantize.  At the moment, these arguments aren't 
considered public, and aren't documented.  (And they're only accessible 
through __round__ anyway, not directly through the round() builtin.)

(3) For one-argument round, ceil, and floor, the only real decision to 
be made is what to do with NaNs and infinities.  The spirit of IEEE 
754/854/754r suggests that an attempt to turn an infinity into an 
integer should signal the 'overflow' floating-point exception, while 
turning a NaN into an integer should signal 'invalid';  correspondingly, 
the patch raises OverflowError or ValueError respectively in these 
situations.

----------
keywords: +patch
Added file: http://bugs.python.org/file10186/decimal_ceilfloor.patch

__________________________________
Tracker <report at bugs.python.org>
<http://bugs.python.org/issue2748>
__________________________________


More information about the Python-bugs-list mailing list