Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Python's Decimal class variable width?

In Python, you can have arbitrarily large integers (though it might take up all your memory to store them). With floats on the other hand they will overflow eventually and you lose precision if you try to make one with too many decimal points.

Which one is the decimal.Decimal class?

Can I have an arbitrary amount of numbers before the decimal point? What about after the decimal point? What are the limits?


1 Answers

Decimal has a user-specified precision; you can modify the current context to specify how many decimal digits must be preserved. Per the docs:

Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem.

That is then followed by an example:

>>> from decimal import *
>>> getcontext().prec = 6
>>> Decimal(1) / Decimal(7)
Decimal('0.142857')
>>> getcontext().prec = 28
>>> Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')

You could turn the precision up to 1,000,000 or more if you really needed it, but math will be slow. In practice, most problems have a point at which you don't need any more precision; NASA stops at 16 digits of pi (15 after the decimal) and at the scale of the entire solar system that has an error margin of only an inch or two for any calculations they care about; they'd need more places to the left of the decimal for magnitude, but for most purposes the default precision of 28 is enough, and turning it up to 40 or 50 should cover any use cases relating to numbers from the real world.

The limit isn't to the left or the right of the decimal place. It's the total number of digits. So if you have Decimal(1000000) + Decimal("0.0001"), with a precision setting of 10 or less, the result will be equal to Decimal(1000000) (it may display additional zeroes to match the precision, but the 0.0001 is dropped). The behavior in cases of rounding or overflow is configurable with signals, so it can set flags, or raise exceptions when it occurs. The docs go into this is in greater detail.

like image 95
ShadowRanger Avatar answered May 30 '26 14:05

ShadowRanger