Python decimal mathematical computing module

Source: Internet
Author: User

Python provides the decimal module for decimal mathematical computation. It has the following features:

  1. Provides the decimal data type and stores it as a decimal number sequence;
  2. 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.
  3. 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.