简体   繁体   中英

Problems with Rounding Decimals (python)

In my program, decimal accuracy is very important.
A lot of my calculations must be accurate to many decimal places (such as 50).

Because I am using python, I have been using the decimal module (with context().prec = 99. ie; Set to have 99 decimal places of accuracy when instantiating a decimal object )
as pythonic floats don't allow anywhere near such accuracy.

Since I wish for the User to specify the decimal places of accuracy of the calculations, I've had to implement several round() functions in my code.
Unfortuneately, the inbuilt round function and the decimal object do not interact well.

round(decimal.Decimal('2.000000000000000000001'),50)

# Number is 1e-21.   There are 21 decimal places, much less than 50.

Yet the result is 2.0 instead of 2.000000000000000000001
The round function is not rounding to 50. Much less!

Yes, I have made sure that the over-rounding does not occur on instantiation of the Decimal object, but after calling round.
I always pass strings representing floats to the Decimal constructor, never pythonic floats.

Why is the round function doing this to me?
(I realise that it was probably originally designed for pythonic floats which can never have so many decimal places, but the documentation claims that the Decimal object integrates perfectly into python code and is compatible with the inbuilt python functions!)

Thanks profusely!
(This has me quite unnerved, since this problem undermines the use of the entire program)

Specs:
python 2.7.1
Windows 7
decimal module (inbuilt)

Since round() coerces its input to a regular binary float, the preferred way to round decimal objects is with the quantize() method:

>>> from decimal import Decimal
>>> d = Decimal('2.000000000000000000001')

>>> d.quantize(Decimal(10) ** -20)     # Round to twenty decimal places
Decimal('2.00000000000000000000')

To chop-off the trailing zeros, apply normalize() to the rounded result:

>>> d = Decimal('2.000000000000000000001')
>>> d.quantize(Decimal(10) ** -20).normalize()
Decimal('2')

The problem, as near as I can determine it, is that round() is returning a Python float type, and not a Decimal type. Thus it doesn't matter what precision you set on the decimal module, because once you call round() you no longer have a Decimal .

To work around this, you'll probably have to come up with an alternative way to round your numbers that doesn't rely on round() . Such as Raymond's suggestion.

You may find this short ideone example illustrative: http://ideone.com/xgPL9

Try the following...

from decimal import Decimal, ROUND_HALF_UP, getcontext

getcontext().prec = 51

def round_as_decimal(num, decimal_places=2):
    """Round a number to a given precision and return as a Decimal

    Arguments:
    :param num: number
    :type num: int, float, decimal, or str
    :returns: Rounded Decimal
    :rtype: decimal.Decimal
    """
    precision = '1.{places}'.format(places='0' * decimal_places)
    return Decimal(str(num)).quantize(Decimal(precision), rounding=ROUND_HALF_UP)

round_as_decimal('2.000000000000000000001', decimal_places=50)

Hope that helps!

Using round() for any purpose has difficulties:

(1) In Python 2.7, round(Decimal('39.142')) produces 39.14 ie a float; 3.2 produces a Decimal.

>>> import decimal; round(decimal.Decimal('2.000000000000000000001'),50)
2.0   <<<=== ***float***

(2) round() has only one rounding mode; Decimal.quantize has many.

(3) For all input types, the single rounding mode changed: Python 2.7 rounds away from 0 (expected in most business applications) whereas Python 3.2 rounds to the nearest even multiple of 10**-n (less expected in business).

Use Decimal.quantize()

As stated above, round() returns a float if provided with a Decimal. For exact calculations, I suggest to do them with not rounded down Decimals, and for rounding the final result, use a function:

    def dround(decimal_number, decimal_places):
        return decimal_number.quantize(Decimal(10) ** -decimal_places)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM