Python provides the decimal module for decimal mathematical computation. It has the following features:
- Provides the decimal data type and stores it as a decimal number sequence;
- Bounded precision: the number of digits used to store numbers is fixed and can be set through decimal. getcontext (). prec = x. Different numbers can have different precision.
- Floating point: the decimal point is not fixed (but the digits are fixed)
Decimal construction:
Decimal. Decimal can be constructed using integers, strings, or tuples. For floating point numbers, you must first convert them to strings.
Context of decimal:
Decimal works in an independent context. You can use getcontext to obtain the current environment. For example, you can use decimal. getcontext (). prec to set the decimal precision (28 by default ):
>>> from decimal import Decimal as D>>> from decimal import getcontext >>> getcontext()Context(prec=6, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[Rounded, Inexact], traps=[DivisionByZero, InvalidOperation, Overflow])>>> getcontext().prec = 6 >>> D(1)/D(3) Decimal('0.333333')
Performance Comparison Between decimal and float:
$: python -mtimeit -s 'from decimal import Decimal as D' 'D("1.2")+D("3.4")'$: python -mtimeit -s 'from decimal import Decimal as D' '1.2+3.4'
I tested the former in a virtual machine, which consumes KB of time, but it is worthwhile in some operations (such as financial operations, however, if you want to perform hundreds of operations on non-integers, you should always use float.