codekingpro/portable-devtools
114k
1"""Decimal fixed-point and floating-point arithmetic.2 3This is an implementation of decimal floating-point arithmetic based on4the General Decimal Arithmetic Specification:5 6 http://speleotrove.com/decimal/decarith.html7 8and IEEE standard 854-1987:9 10 http://en.wikipedia.org/wiki/IEEE_854-198711 12Decimal floating point has finite precision with arbitrarily large bounds.13 14The purpose of this module is to support arithmetic using familiar15"schoolhouse" rules and to avoid some of the tricky representation16issues associated with binary floating point. The package is especially17useful for financial applications or for contexts where users have18expectations that are at odds with binary floating point (for instance,19in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead20of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected21Decimal('0.00')).22 23Here are some examples of using the decimal module:24 25>>> from decimal import *26>>> setcontext(ExtendedContext)27>>> Decimal(0)28Decimal('0')29>>> Decimal('1')30Decimal('1')31>>> Decimal('-.0123')32Decimal('-0.0123')33>>> Decimal(123456)34Decimal('123456')35>>> Decimal('123.45e12345678')36Decimal('1.2345E+12345680')37>>> Decimal('1.33') + Decimal('1.27')38Decimal('2.60')39>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')40Decimal('-2.20')41>>> dig = Decimal(1)42>>> print(dig / Decimal(3))430.33333333344>>> getcontext().prec = 1845>>> print(dig / Decimal(3))460.33333333333333333347>>> print(dig.sqrt())48149>>> print(Decimal(3).sqrt())501.7320508075688772951>>> print(Decimal(3) ** 123)524.85192780976896427E+5853>>> inf = Decimal(1) / Decimal(0)54>>> print(inf)55Infinity56>>> neginf = Decimal(-1) / Decimal(0)57>>> print(neginf)58-Infinity59>>> print(neginf + inf)60NaN61>>> print(neginf * inf)62-Infinity63>>> print(dig / 0)64Infinity65>>> getcontext().traps[DivisionByZero] = 166>>> print(dig / 0)67Traceback (most recent call last):68 ...69 ...70 ...71decimal.DivisionByZero: x / 072>>> c = Context()73>>> c.traps[InvalidOperation] = 074>>> print(c.flags[InvalidOperation])75076>>> c.divide(Decimal(0), Decimal(0))77Decimal('NaN')78>>> c.traps[InvalidOperation] = 179>>> print(c.flags[InvalidOperation])80181>>> c.flags[InvalidOperation] = 082>>> print(c.flags[InvalidOperation])83084>>> print(c.divide(Decimal(0), Decimal(0)))85Traceback (most recent call last):86 ...87 ...88 ...89decimal.InvalidOperation: 0 / 090>>> print(c.flags[InvalidOperation])91192>>> c.flags[InvalidOperation] = 093>>> c.traps[InvalidOperation] = 094>>> print(c.divide(Decimal(0), Decimal(0)))95NaN96>>> print(c.flags[InvalidOperation])97198>>>99"""100 101try:102 from _decimal import *103 from _decimal import __version__ # noqa: F401104 from _decimal import __libmpdec_version__ # noqa: F401105except ImportError:106 import _pydecimal107 import sys108 _pydecimal.__doc__ = __doc__109 sys.modules[__name__] = _pydecimal110 