Adventures in Machine Learning

Precise Number Manipulation in Python: Using the Decimal and Fraction Modules

Python has become one of the most popular programming languages in recent years. Its versatility, simplicity, and ease of use have made it a go-to tool for developers and data scientists alike.

One of the critical components of programming is working with data, particularly numerical data. Python offers a range of numeric data types, and in this article, we will explore some of the important aspects of working with numeric data in Python.

Python Numeric Data Types

Python supports a range of numeric data types, each designed for a specific purpose.

Integer Numbers – This is one of the most common types of numeric data in Python.

Integers are used for whole numbers and are denoted by the keyword ‘int.’ As an example, we can assign an integer value to a variable roll_no as follows:


roll_no = 10


Float Numbers – These are used for decimal numbers and are denoted by the ‘float’ keyword. Float numbers are particularly useful when performing calculations that require decimal precision.

We can assign a float value to a variable ‘x’ as follows:


x = 3.14


Complex Numbers – These are numbers with both real and imaginary components. They are denoted using the ‘complex’ keyword.

As an example, we can assign a complex value to a variable ‘c’ as follows:


c = 3 + 4j


Hexadecimal and Octal Numbers – Python also supports the use of hexadecimal and octal numbers. These are useful when working with binary data.

Octal numbers are denoted with the ‘o’ keyword, while hexadecimal numbers are denoted using the ‘0x’ prefix. As an example:


octal = 0o123

hexadecimal = 0x123


Number Type Conversion – When working with multiple data types, it is often necessary to convert from one type to another.

Python provides two types of type conversion – implicit and explicit. Implicit Type Conversion occurs when Python converts one data type to another without the programmer’s input.

This is usually done to prevent data loss or runtime errors. For example:


a = 10

b = 3.25

c = a + b # Implicit conversion to float


Explicit Type Conversion is when the programmer specifies the desired data type.

This is done using constructor functions such as ‘int,’ ‘float,’ and ‘complex.’ For instance:


a = 10.45

b = int(a) # Explicit conversion to integer


Math Module Methods to work with Numerical Data

Python has a built-in ‘Math’ module that provides a range of functions to work with numerical data. These include:

Ceil() and Floor() – These are functions that round off numbers.

Ceil rounds up to the nearest integer while floor rounds down. As an example:


import math

x = 3.14

y = math.ceil(x) # y will be 4

z = math.floor(x) # z will be 3


Degrees() and Radians() – These functions convert angles from degrees to radians and vice versa. They are particularly useful when working with trigonometric functions in radians.

For example:


import math

angle_in_deg = 90

angle_in_rad = math.radians(angle_in_deg)


Sin() and Cos() These are trigonometric functions for calculating sine and cosine respectively. As an example:


import math

angle_in_rad = math.radians(30)

sin_value = math.sin(angle_in_rad) # sin_value will be 0.5

cos_value = math.cos(angle_in_rad) # cos_value will be 0.8660


Factorial() This function is used to calculate the factorial of a given number. The factorial of a number is the product of all the integers from 1 to that number.

For instance:


import math

number = 5

result = math.factorial(number) # result will be 120 (5*4*3*2*1)


Fabs() and Trunc() – These functions are used to calculate the absolute value of a number. However, the ‘fabs’ function always returns a positive value, while the ‘trunc’ function returns the integer part of the number.

As an example:


import math

x = -2.34

y = math.fabs(x) # y will be 2.34

z = math.trunc(x) # z will be -2


Pow() and Log() – The ‘pow’ function calculates the power of a given number, while the ‘log’ function returns the natural logarithm of a number. As an example:


import math

x = 2

y = 3

z = math.pow(x, y) # z will be 8 (2^3)

a = 2.7183

b = math.log(a) # b will be 1.0


Checking Functions – The ‘Math’ module also includes a range of functions to check the validity of a given number such as isfinite, isinf, isnan, and isclose.


In conclusion, Python offers a wide range of Numeric Data Types and Math module functions making it an ideal tool for processing and manipulating numerical data. The functions we covered in this article are just a few examples of what is available in Python.

By leveraging Python’s powerful numeric data features, developers can build complex algorithms that make use of numerical data with ease. Python is a versatile programming language that offers several data types and modules to handle numeric data.

In addition to the standard numeric data types, Python has a Decimal module that provides a high-precision way of working with decimal numbers. In this expansion, we will explore the Decimal module, providing in-depth knowledge on how to create, perform mathematical operations, and format numbers with it.

Creating a Decimal Number

The Decimal module is useful in applications where floating-point rounding errors can lead to inaccurate calculations and/or readability problems. It offers a precise and flexible way of working with decimal numbers.

The Decimal is constructed by providing a tuple of three integers: a sign (0 for positive and 1 for negative), a tuple of digits, and the exponent of 10 to raise before the final result. Here is an example:


from decimal import Decimal

x = Decimal((0, (1, 4, 2), -2))

print(x) # Output: 1.42


In the above example, the tuple of digits represents the value of the decimal number as (1 * 10^1 + 4* 10^0 + 2 * 10^-1). As such, the above code block outputs 1.42

Mathematical Operations

The Decimal Module provides several methods for performing mathematical operations such as addition, subtraction, multiplication, and division on decimal numbers. For instance:


x = Decimal(2)

y = Decimal(3)

# Additions

z = x + y # z is 5

# Subtraction

z = x – y # z is -1

# Multiplication

z = x * y # z is 6

# Division

z = x / y # z is 0.6666..


One significant difference between the regular floating-point arithmetic and Decimal arithmetic is that the Decimal module allows you to specify the precision to which the result should be calculated. “`

from decimal import Decimal

x = Decimal(1)

y = Decimal(7)

z = x / y

print(z) # Output: 0.1428571428571428571428571429


In the above example, the output is a rational number with an infinite recurring decimal. The Decimal module also provides the square root and logarithmic functions.


from decimal import Decimal, getcontext

getcontext().prec = 6 # Set precision to six decimal places

x = Decimal(5)

y = x.sqrt() # Calculate the square root of 5

print(y) # Output: 2.23607

# Calculate logarithm of a number

x = Decimal(100)

y = x.ln() # Natural logarithm i.e. log base e of 100

print(y) # Output: 4.60517


Fraction Module Methods

The Fraction module in Python also provides operations for handling precise fractional numbers. The module provides three functions that can be used to convert decimal numbers to fractions, find the closest fraction to a given decimal value, and format the fraction.


from fractions import Fraction

# Convert decimal to fraction

x = Fraction(‘3.4’) # Output: 17/5

y = Fraction(‘1.25’) # Output: 5/4

# Closest fraction to decimal

x = Fraction(‘3.14159265359’).limit_denominator(10)

print(x) # Output: 22/7

# Formatting fractions

x = Fraction(3, 7)

y = Fraction(1, 3)

print(‘{0}/{1}’.format(x.numerator, x.denominator)) # Output: 3/7

print(‘{0:.2f}’.format(float(y))) # Output: 0.33


Printing Numbers in Different Formats

The Decimal module offers ways to format numbers in different formats to make it more readable. The `format` method is used to specify how the numbers should be displayed.

We can display the Decimal module number in different formats such as zero-padded, scientific notation, and exponential notation. “`

from decimal import Decimal

x = Decimal(‘123.456’)

print(format(x, ‘0>10’)) # Zero-padded Output: 0123.4560

print(format(x, ‘e’)) # Scientific Notation Output: 1.234560e+02

print(format(x, ‘.2e’)) # Exponential Notation Output: 1.23e+02


The zero-padded format is useful when you want to create an output that always has a certain width. The scientific and exponential notation formats are useful when you want to represent large or small numbers in a readable and compact format.


The Decimal module in Python provides a way of working with decimal numbers in a precise and flexible way. With this module, you can perform mathematical operations with decimals to a specific precision, convert decimals to fractions and format your numerical resolutions in more readable formats.

The Fraction module provides useful methods that you can use to approximate and format fractions in several ways. By utilizing these modules properly, developers can avoid problems with floating-point rounding errors and offer a higher level of precision in numerical calculations.

In conclusion, Python’s Decimal module offers developers a flexible and precise way of working with decimal numbers. By using this module, programmers can eliminate floating-point rounding errors and improve the readability and accuracy of their calculations.

The Fraction module also offers several methods for dealing with precise fractional numbers. Additionally, formatting numbers in different formats is made possible by the format method of the Decimal module.

The takeaway from this article is that by making use of these powerful modules, developers can build more sophisticated programs and applications suited to handling arithmetic and mathematical functions at a higher level of precision.

Popular Posts