Fractions module introduction

Posted by Afsal on 18-Aug-2023

Hi Pythonistas!,

While working with numbers where we need more precision like financial/ scientific values float cannot be a better option due to rounding errors. Today we are going to learn a package called fractions. The built-in fractions module provides a powerful toolkit for handling rational numbers, allowing you to maintain precision and accuracy in your calculations. Let's dive into the code

Creating Fractions

from fractions import Fraction

a = Fraction(3, 4)

print(a)

b = Fraction(1, 2)

print(b)

c = Fraction(2, 4)

print(c)

Output

3/4

1/2

1/2

Note: fractions module does the simplification of the fraction during the creation. If we check 2/4 converted into 1/2

Converting Floats to Fractions

a = Fraction(0.75)

print(a)

Output

3/4

Converting Fractions to Floats

a = Fraction(3, 4)

print(float(a))

Output

0.75

Note: This may lead to rounding errors

Performing arithmetic operations

a = Fraction(3, 4)

b = Fraction(1, 2)

print("Sum: ", a+b)

print("Product", a*b)

print("Difference", a-b)

print("Division", a/b)

Output

Sum:  5/4

Product 3/8

Difference 1/4

Division 3/2

The fractions module is a powerful tool for scenarios where you need precise and exact numerical representations. It can be precious in fields that require accurate calculations and in situations where fractions are a natural and meaningful way to express values.

Hope you have learned something from this post. Please share your suggestions with afsal@parseltongue.co.in