Python Tutorial: Python Decimal Module – Python Numbers #27

Python

Video is ready, Click Here to View ×


Read more about the Python Decimal Module at http://learnpythontutorial.com/python-decimal-module-python-tutorial/

Python Decimal Module
In the previous two Python tutorials, we looked at issues that arise when working collaboratively with floating point numbers in the Python programming language. When working with floating point numbers we have seen that Python sometimes returns a value that we are not suspecting. This is doesn’t happen often but when we get a number that is a few ten…

8 thoughts on “Python Tutorial: Python Decimal Module – Python Numbers #27

  1. Do we have any way, to set the precision as per required, through out the programme …….bcos setting the PRECISION with GETCONTEXT is not at all a good idea and calling the QUANTIZE every time is not simple.. …………AND I WOULD LIKE TO THANK YOU FOR YOUR VALUABLE TUTORIALS …THOUGH IAM FROM A REMOTE AREA YOUR TUTORIAL MADE THE JoB EASY

  2. One of the primary benefits of using the decimal module is the ability to avoid many floating point problems from the start. But using Decimal(7.6) creates a floating point approximation of 7.6 and then passes this approximation into the Decimal constructor–the precision is immediately lost. The example would benefit from using Decimal("7.6"), etc.–this creates a true 7.6 value that can be operated on without fudging the result by lowering the decimal precision of the context:

    >>> from decimal import Decimal
    >>> Decimal('7.6') + Decimal('8.7')
    Decimal('16.3')

    There are no rounding issues to correct when you use precise values (the strings representations) to instantiate the Decimal objects. Yes, it's nice that the module gives us the tools to manage rounding issues but the ability to avoid them in the first place is the decimal module's real benefit.

Leave a Reply

Your email address will not be published. Required fields are marked *