Decimal functions in Python
The Decimal module in Python has ample functions to do the arithmetic of decimal floating-point numbers. So it provides support for fast correctly rounded floating-point arithmetic. There are many advantages to using this module :
- Computers must provide an arithmetic that works in the same way as people learned in school!.
- Decimal numbers can be represented exactly as we have learned in school arithmetics, for example:
#As in simple computer arithmetic print(1.1 + 2.2)
While using this module we can alter the precision using the getcontext() method.
#Using the school-like arithmetic calculation from decimal import * getcontext().prec = 2 #earlier print(1.1 + 2.2) #after using decimal print(Decimal(1.1) + Decimal(2.2))
3. We have studied exact arithmetic in school, for example, floating-point returns 0.1+0.1+0.1 -0.3 exactly equal to zero, while binary floating-point returns near to zero 5.551115123172e-017.
4. It also considers the notion of significant places hence useful for monetary applications.
For example, 1.5 +1.5 equals 2.50 last zero is kept to consider significant place.
Decimal numbers are immutable. It has signs, coefficients, and exponents. To preserve the significance coefficients digits do not truncate the trailing zeroes. Decimals also include special numbers such as infinity,-infinity and nans, etc.
Let’s have a look at some important operations and how the decimal module works:
Methods defined in Python Decimal Module
- sqrt():- Computes the square root of decimal function.
- exp() :- Computes the exponent of decimal function,(e^x).
- ln() :- Computes the natural log of decimal function.
- log10():-Computes logarithm of base 10 of decimal function.
#Calculating the square root print(Decimal(4).sqrt()) #Calculating the Exponential print(Decimal(4).exp()) #Calculating the natural logarithm print(Decimal(4).ln()) #Calculating the logarithm to base 10 print(Decimal(4).log10()
output: 2 54.59815003314423 1.386294361119890610 0.602059991327
- quantize():- Rounds the data to a fixed exponent.
- min():-Computes minimum of two decimal numbers.
- max():-Computes maximum of two decimal numbers.
- compare():-Compares two decimal numbers. It returns 1 if 1st decimal number is greater,-1 if smaller and 0 if 1st and 2nd numbers are equal.
#Quantizing decimal numbers print(Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)) print(Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)) #Computing max, min a = Decimal(10) b = Decimal(10.5) print(a.max(b)) print(a.min(b)) #Copmaring numbers print(a.compare(b))
output: 7.32 8 10.5 10 Decimal(-1)
Since decimal module provides a lot many such methods and discussing all of them is out of the scope of this blog, if you are interested to explore more then you may refer to this official documentation: