Python Decimal Module | Scaler Topics

Source: Python Decimal Module | Scaler Topics

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials

Python Course for Beginners With Certification: Mastering the Essentials
byRahul Janghu

144551
4.90

Start Learning

Topics Covered

Overview

There are several different numeric data types in Python, including int, float, and complex numbers, but due to floating point numbers’ machine-dependent nature, we need a more precise data type. This article examines the Python decimal module, which implements decimal numbers with precision of up to 28 digits.

Python Decimal Module

With the Python decimal module, decimal floating point arithmetic is carried out at high speed. In Python, numbers that contain decimal points are always treated as double-precision floating-point numbers. Decimal points have a smaller range than floats, but more precision. For monetary and financial calculations, it is appropriate. Also, it is more similar to how humans handle numbers.

Decimal modules have a precision that can be adjusted to any size necessary for a given problem, unlike hardware-based binary floating points. By default, precision is set to 28 places. There are some values that cannot be accurately represented by the float data type. If the 0.1 value is stored in a float variable (binary floating point value), we get only an approximation. In the same way, 1/3 cannot be exactly represented in a decimal floating point.

Decimal types are generally more suitable for financial and monetary calculations, while double/float types are better for scientific calculations.

Basic Mathematical Operations Using Python Decimal Module

The Decimal constructor is used in Python to convert numbers into decimal types. Below is a code sample that illustrates the difference between division on integers and decimals.

from decimal import Decimal
i = 8
j = 9
k = i / j
d = Decimal(i) / Decimal(j)
print (k, type(k))
print (d, type(d))

Importing the Decimal class from the decimal module is the first statement. Next, we create two variables called “i” and “j”, each containing some values. A value is stored in the variable “k” when i and j are divided by each other. Once the numbers have been converted to decimal types, the process is repeated.

You will get the following output when you run the above code sample:

0.8888888888888888 <class 'float'>

0.8888888888888888888888888889 <class 'decimal.Decimal'>

This output shows that float type objects have less precision than decimal type objects because their approximation method is much more aggressive. A decimal-type number in Python can display up to 28 numbers by default. By calling the “getcontext” method in the decimal module, you can change this value according to your needs.

from decimal import Decimal
from decimal import getcontext

getcontext().prec = 40
i = 8
j = 9
k = i / j
d = Decimal(i) / Decimal(j)
print (k, type(k))
print (d, type(d))

We have imported the getcontext function and increased the precision to 40 positions in the above code sample. By using getcontext, you can see what the current context is in the thread and change some of the default settings for the decimal module. If you run the above code sample, you should see the following output:

0.8888888888888888 <class 'float'>

0.8888888888888888888888888888888888888889 <class 'decimal.Decimal'>

In Python, you can perform any arithmetic operation with decimal type objects that you can with float type objects. In decimal-type objects, there are a large number of trailing decimal numbers, which can be particularly useful for financial, accounting, mission-critical scientific applications, and so forth.

A decimal number can be created from a float, integer, or string containing a number by calling the main Decimal constructor.

Rounding off Numbers Using Python Decimal Module

round() function returns a floating point number with the specified number of decimals as a rounded version of the original number.

In the default case, the function returns the nearest integer, since the number of decimals is 0.

In the Decimal module, rounding types are available, as shown below:

Rounding Description
ROUND_CEILING This will round towards Infinity
ROUND_DOWN This rounds the value towards zero
ROUND_FLOOR This will round towards Infinity
ROUND_HALF_DOWN This will round to the nearest value going towards zero
ROUND_HALF_EVEN The value is rounded to the nearest even integer
ROUND_HALF_UP This will round to nearest value going away from zero
ROUND_UP This will round values away from zero
ROUND_05UP Whenever the last number is either zero or five, the number is rounded away from zero

Here is an example to demonstrate all the functions mentioned above

import decimal
from decimal import Decimal
from decimal import getcontext
getcontext().prec = 4
getcontext().rounding = decimal.ROUND_FLOOR
print (Decimal(4.518) + Decimal(0))
getcontext().rounding = decimal.ROUND_CEILING
print (Decimal(4.518) + Decimal(0))
getcontext().rounding = decimal.ROUND_HALF_DOWN
print (Decimal(2.805) + Decimal(0))
getcontext().rounding = decimal.ROUND_HALF_UP
print (Decimal(2.875) + Decimal(0))
getcontext().rounding = decimal.ROUND_UP
print (Decimal(5.875) + Decimal(0))
getcontext().rounding = decimal.ROUND_DOWN
print (Decimal(4.805) + Decimal(0))
getcontext().rounding = decimal.ROUND_HALF_EVEN
print (Decimal(1.457) + Decimal(0))
getcontext().rounding = decimal.ROUND_05UP
print (Decimal(2.555) + Decimal(0))

Output:

4.517
4.518
2.805
2.875
5.875
4.804
1.457
2.556

a. Using the Quantize Method

Decimal(“1.0”) in .quantize() specifies how many decimal places the number should be rounded to. Because 1.0 can only have one decimal place, the number 2.35 can also only have one decimal place. The default strategy is to round half to even, so 2.4 is the result.

import decimal
from decimal import Decimal
dec = Decimal("2.35").quantize(Decimal("1.0")) 
print(dec)

Output:

2.4

Another example is shown below

As we have specified the quantize to two we get 3.88 as result

import decimal
from decimal import Decimal
dec = Decimal("3.885").quantize(Decimal("1.00"))
print(dec)

Output:

3.88

Using Python Module to Compare Two Numbers

The “compare” method in the decimal module allows you to compare two decimal-type objects. Its usage is illustrated in the following examples.

from decimal import Decimal
print (Decimal(2.2).compare(Decimal(2.1)))
print (Decimal(2.0).compare(Decimal(2.1)))
print (Decimal(2.0).compare(Decimal(2.0)))

The following output should be obtained after running the code sample above:

1
-1
0

Ton order to compare two decimal-type objects, you must supply the other number as an argument. Depending on the numbers being compared, a value of 0, 1, or -1 will be returned. If the value is 0, both numbers are equal, if it is 1, the first number is greater than the second, and if it is -1, the first number is less.

Important Function in Python Decimal Module

a. exp() Function

It’s pretty straightforward to follow the code sample. Numbers are rounded off with a precision of two digits. Changing the rounding method is done via the “rounding” object (part of the main context).

The exp() function – Exponent calculation

The exp() function is used to calculate the exponent value of a decimal point number, e.g. x^2

Syntax:

decimal.Decimal(decimal-number).exp()

Example:

import decimal
dec = decimal.Decimal(12.48)
print(dec)
#Here we are finding the e^x for the decimal number
print('e^x is: ' + str(dec.exp()))

Output:

12.480000000000000426325641456060111522674560546875
e^x is: 263023.8522464959270659735531

b. sqrt() Function

Sqrt() is a function that calculates and returns the square root value of the decimal number that has been passed to it.

Syntax:

decimal.Decimal(decimal-number).sqrt()

Example:

import decimal
dec = decimal.Decimal(12.48)
print(dec)
#Here we are finding the Square Root of the decimal number
print('Square Root is: ' + str(dec.sqrt()))

Output:

12.480000000000000426325641456060111522674560546875
Square Root is: 3.532704346531138802245458702

Logarithmic Functions

In the Decimal module, we can compute decimal point numbers’ logarithmic values using the below functions –

  • decimal.ln()
  • decimal.log10()

In the following example, decimal.ln() returns the natural log value of a decimal number –

decimal.Decimal(decimal-number).ln()

By calling decimal.log10(), you will obtain the log value for the decimal number you passed.

decimal.Decimal(decimal-number).log10()

Example:

import decimal
dec = decimal.Decimal(14.48)
print(dec)
#Here we are finding the logarithmic value with base e
print('ln(x) is: ' + str(dec.ln()))
#Here we are finding the logarithmic value with base 10
print('log(x) is: ' + str(dec.log10()))

Output:

14.480000000000000426325641456060111522674560546875
ln(x) is: 2.672768386957570336497179047
log(x) is: 1.160768561861128108717622901

d. The compare() Function

Based on the conditions set forth below, decimal.compare() returns values based on the comparison of two decimal point numbers.

  • In the case where the first decimal number is smaller than the second decimal number, it returns -1.
  • In the case where the first decimal number exceeds the second decimal number, it returns 1.
  • When both decimal points are equal, it returns 0.

Syntax:

Decimal.compare()

Example:

import decimal
# Here we are comparing when both are equal
print('Compare value: ' + str(decimal.Decimal(-1.3).compare(decimal.Decimal(-1.3))))
# Here we are comparing when first one is smaller
print('Compare value: ' + str(decimal.Decimal(-1.3).compare(decimal.Decimal(7.71))))
# Here we are comparing when first one is greater
print('Compare value: ' + str(decimal.Decimal(-3.3).compare(decimal.Decimal(-15.25))))

Output:

Compare value: 0
Compare value: -1
Compare value: 1

e. The copy_abs() Function

Using decimal.copy_abs(), you can obtain the absolute values of signed decimal numbers.

Syntax:

decimal.Decimal(signed decimal number).copy_abs()

Example:

import decimal as d
dec = d.Decimal(-100.12)
print("Value 1: ",dec)
absolute_value = dec.copy_abs()
print("Absolute value of the given decimal number: ",absolute_value)

Output:

Value 1:  -100.1200000000000045474735088646411895751953125
Absolute value of the given decimal number:  100.1200000000000045474735088646411895751953125

f. Max and Min functions

For computing the minimum and maximum values of decimal point numbers, the Python decimal module provides the following functions.

min() function: Gets the smallest value between two decimal places.

max() function: Gets the maximum value of two decimal numbers.

Syntax for “min()” function-

decimal1.min(decimal2)

Syntax for “max()” function

decimal1.max(decimal2)

Example:

import decimal
dec1 = decimal.Decimal(5.3)
print(dec1)
dec2 = decimal.Decimal(-9.23)
print(dec2)
# Here we are showing the minimum and maximum values
print('Minumum: ' + str(dec1.min(dec2)))
print('Maximum: ' + str(dec2.max(dec1)))

Output:

5.29999999999999982236431605997495353221893310546875
-9.230000000000000426325641456060111522674560546875
Minumum: -9.230000000000000426325641456
Maximum: 5.299999999999999822364316060

g. Logical Operations with Decimal Module

Logic operations such as AND, OR, XOR can be performed on decimal numbers using the decimal module.

logical_and() function: This function performs logical AND operations on two decimal numbers and produces the result.

logical_or() function: This function performs logical OR operations on two decimal numbers and produces the result.

logical_xor() function: This function performs logical XOR operations on two decimal numbers and produces the result.

This is the syntax for the function logical_and():

decimal1.logical_and(decimal2)

This is the Syntax for logical_or() function-

decimal1.logical_or(decimal2)

This is the Syntax for logical_xor() function-

decimal1.logical_xor(decimal2)

Example:

import decimal as d
dec1 = d.Decimal(1001)
dec2 = d.Decimal(1111)
print("The Value 1: ",dec1)
print("The Value 2: ",dec2)
AND = dec1.logical_and(dec2)
print("The logical AND value of the two decimals: ",AND)
OR = dec1.logical_or(dec2)
print("The logical OR value of the two decimals: ",OR)
XOR = dec1.logical_xor(dec2)
print("The logical XOR value of the two decimals: ",XOR)

Output:

The Value 1:  1100
The Value 2:  1010
The logical AND value of the two decimals:  1000
The logical OR value of the two decimals:  1110
The logical XOR value of the two decimals:  110

Conclusion

  • Use the Python decimal module for fast and correct floating-point arithmetic with decimal numbers.
  • To create Decimal objects using strings, integers, and tuples, use the Decimal class in the decimal module.
  • The precision and rounding mechanism of Decimal numbers is controlled by their context.
  • The math module does not define all methods for the Decimal class. Nevertheless, if the Decimal arithmetic methods are available, you should use them.

Leave a Reply

The maximum upload file size: 500 MB. You can upload: image, audio, video, document, spreadsheet, interactive, other. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here