Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rational
python
division
communitycreator

How to represent rational numbers in Python

Ammar Ahmad Farid

Overview

There are two types of division in Python:

  1. Floating-point division: When we use the / operator to divide two integer numbers (x/y), we will get a floating-point number as the result.

  2. Floor division: When we use the // operator to divide two integers (x//y), we will get an integer number. This type of division is also known as integer division.

Note: In mathematics, a rational number can be expressed as a fraction pq\dfrac{p}{q}, where pp is an integer in the numerator and qq is an integer in the denominator, and qq \neq 0.

In Python, rational numbers exist and can be represented with the use of the fractions module. To use this module, we have to first import it into our program by running the following command:

from fractions import Fraction

Syntax

Fraction(22,7)

Parameters

In the Fraction() constructor, the first parameter is the numerator, and the second parameter is the denominator.

Code

from fractions import Fraction
print(Fraction(22,7))
Using the Fraction() constructor

RELATED TAGS

rational
python
division
communitycreator

CONTRIBUTOR

Ammar Ahmad Farid
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring