Rational Numbers in Python

In this tutorial, we will learn how to check a number is a rational number or not in Python with some cool and easy examples.

I know, you have faced so many problems in Python to check the number is rational or not. Python Language has so many inbuilt modules so that you can ease your work.

What is Rational Number

let’s learn:

Any number which can be expressed in the form of p/q, where p and q are integers and q is not equal to 0(i.e q!= 0), is called a rational number.

Examples :

  1. 2/5
  2. 4/3
  3. 3/1
  4. 2.14

Python module for rational number

There is the inbuilt module for a rational number in Python. This module has a fraction class and two objects, shown below:

from fractions import Fraction
Fraction(num, denom)

Providing value to object of Fractional class:

from fractions import Fraction 
rational1 = Fraction(7,2) 
print(rational1)
rational2 = Fraction(12,4) 
print(rational2)
rational3 = Fraction(11,3) 
print(rational3)

Points to remember:

  1. If the value of denominator = 0, it will throws ZeroDivisionError.
  2. After division numerator and denominator will be reduced to the shortest form.
Output:
7/2
3
11/3

The Fraction constructor also receives string parameter, if and only if contains valid numeric representation.

Examples:

from fractions import Fraction
p = Fraction('1')
print(p)
q = Fraction('2')
print(q)
Output:
1
2

There are two attributes numerator and denominator of Fraction, which a user can access independently.

rational1 = Fraction(7,2)
print("numerator",rational1.numerator)
print("denominator",rational1.denominator)
rational2 = Fraction(12,4)
print("numerator",rational2.numerator)
print("denominator",rational2.denominator)
Output:
numerator 7
denominator 2
numerator 3
denominator 1

In this article, we learned about the rational number in python and using of Fraction module and its various attributes. If you have any queries please comment below.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *