English 中文(简体)
圆 Dec(平)问题
原标题: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)

最佳回答

正如我可以确定的那样,问题在于:round(>>正在回归一个float的类型,而不是一个Decimal的类型。 因此,你在<代码>decimal模块上设定了何种精确性,因为一旦你打电话round(),你不再有<>Decimal。

为了围绕这一点开展工作,你或许必须找到一种替代方法,以取代不依赖<条码>的编号。 如雷蒙德的建议。

http://ideone.com/xgPL9>。

问题回答

round(/em> <http://docs.python.org/library/decimal.html#decimal.Decimal.quantize” rel=“noreferer”>quantize(>>>>>>>>。 方法:

>>> 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 )

引言如下......

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)

希望帮助!

<round(> for any purpose has problems:

(1) 在Aval 2.7, 圆(Decimal(39.142))产生39.14,即浮动;3.2 产生 Dec。

>>> 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)




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...