Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | os.closerange() method
Next article icon

Python math library | isclose() method

Last Updated : 19 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In the Python math module, math.isclose() the method is used to determine whether two floating point numbers are close in value. To use this function in Python you must import the math module.

Syntax: isclose(a, b, rel_tol = 1e-09, abs_tol 0.0) Parameters: rel_tol: maximum difference for being considered “close”, relative to the magnitude of the input values abs_tol: maximum difference for being considered “close”, regardless of the magnitude of the input values -> rel_tol and abs_tol can be changed by using keyword argument, or by simply providing directly as according to their positions in the parameter list. Return Value : Return True if a is close in value to b, and False otherwise.

Without Using any Tolerance

For the values to be considered close, the difference between them must be smaller than at least one of the tolerances. If both torelances are provided, the absolute tolerance is checked first, and if exceeded the the relative tolerance is checked.

Python3




# Example 1 : Without specifying any tolerance
 
# By default, math.isclose() applies a relative tolerance of 1e-09 = 0.0000000010
 
# Importing Math module
import math
 
# printing whether two values are close or not
print(math.isclose(2.005, 2.005)) # True,values are exact
print(math.isclose(2.005, 2.004)) # False, relative difference > default rel_tol
print(math.isclose(2.006, 2.005)) # False, relative difference > default rel_tol
 
# calculating relative differences:
# |2.005 - 2.004|/((2.005 - 2.004)/2) = 0.0005
# |2.006 - 2.005|/((2.006 - 2.005)/2) = 0.0005
 
 

Output:

True False False

Using Absolute Tolerance

The absolute difference between the two values is checked against specified absolute tolerance (abs_tol), if the abs_tol is exceed mathisclose() returns False and True if otherwise.

Python3




# Example 2 : Using absolute tolerances
 
# Importing Math module
import math
 
# printing whether two values are close or not
print(math.isclose(2.005, 2.125, abs_tol = 0.25)) # True, absolute difference < abs_tol
print(math.isclose(2.547, 2.0048, abs_tol = 0.5)) # False, absolute difference > abs_tol
print(math.isclose(2.0214, 2.00214, abs_tol = 0.02)) # True, absolute difference < abs_tol
 
# calculating absolute differences:
# |2.005 - 2.125|    = 0.12000
# |2.547 - 2.0048|   = 0.54220
# |2.0214 - 2.00214| = 0.01926
 
 

Output:

True False True  

You can change absolute tolerance, as in above case absolute tolerance is different in all three cases.

Using Relative Tolerance

By default, math.isclose() provides a default rel_tol = 1e-09 = 0.0000000010. If no tolerance is specified then this is used.

However, rel_tol can be specified to meet requirements.

Python3




# Example 3 : Using relative tolerances
import math  # isclose() is domiciled in the math library
a = 2.005
b = 2.004
 
calc_rel_diff = abs(a - b) / ((a + b) / 2)
print("Calculated relative difference = {:.6f}".format(calc_rel_diff))
print("Default relative difference used in math.isclose() = {:.10f}".format(1e-09))
 
# printing whether two values are close or not without specifying the tolerances. Takes default rel_tol
# Calculated relative difference way above default rel_tol = 1e-09 = 0.0000000010, Returns False
print("Returns: {} --> calc_rel_diff = {} > default rel_tol = {:.10f}".format(math.isclose(a, b), calc_rel_diff, 1e-09))
# specify rel_tol
rel_tol = 5e-04
print("Returns: {}  --> calc_rel_diff = {} < specified rel_tol = {:.4f}".format(math.isclose(a, b, rel_tol=rel_tol),calc_rel_diff, rel_tol))  # Calculated relative difference below default rel_tol = 1e-09 = 0.0000000010
 
 

Output:

Calculated relative difference = 0.000499 Default relative difference used in math.isclose() = 0.0000000010 Returns: False --> calc_rel_diff = 0.0004988775255674181 > default rel_tol = 0.0000000010 Returns: True  --> calc_rel_diff = 0.0004988775255674181 < specified rel_tol = 0.0005

Combining both tolerances

Using both abs_tol (absolute tolerance) and rel_tol (relative tolerance) together in the math.isclose() function allows you to define a more precise and flexible criterion for determining if two numbers are “close enough” based on both absolute and relative considerations.

abs_tol is checked first. If the absolute difference between the numbers is within abs_tol, the function returns True.

If the absolute difference is greater than abs_tol, the function then checks the relative difference based on rel_tol. If the relative difference is within rel_tol, the function returns True.

If neither the absolute tolerance nor the relative tolerance conditions are met, the function returns False.

The example below illustrate a case where the absolute tolerance is exceeded while the relative tolerance is not exceeded giving a positive comparison.

Python3




# Example 4 : Using both tolerances: abs_rel exceeded but the rel_tol not exceeded returning True
import math # isclose() is domiciled in the math library
a = 2.005
b = 2.004
calc_rel_diff = abs(a - b) / ((a + b) / 2)
calc_abs_diff = abs(a-b)
print("Calculated relative difference = {:.6f}".format(calc_rel_diff))
print("Calculated absolute difference = {:.6f}".format(calc_abs_diff))
 
# Specifying both tolerances
abs_rol = 4e-04 # 0.0004
rel_tol = 5e-04 # 0.0005
 
print("Returns: {}  --> Though the calculated absolute difference = {:.6f} > specified abs_tol = {:.6f}, the calc_rel_diff = {:.6f} < specified rel_tol = {:.6f} which is checked last if the absolute difference is exceeded.".format(math.isclose(a, b, rel_tol=rel_tol, abs_tol=abs_rol),calc_abs_diff, abs_rol, calc_rel_diff, rel_tol)) # Calculated relative difference below default rel_tol = 1e-09 = 0.0000000010
 
 

Output:

Calculated relative difference = 0.000499 Calculated absolute difference = 0.001000 Returns: True  --> Though the calculated absolute difference = 0.001000 > specified abs_tol = 0.000400, the calc_rel_diff = 0.000499 < specified rel_tol = 0.000500  which is checked last if the absolute difference is exceeded. 

If both tolerances were exceeded then math.isclose() would return False.



Next Article
Python | os.closerange() method
author
sanjeev2552
Improve
Article Tags :
  • Python
  • Python math-library-functions
Practice Tags :
  • python

Similar Reads

  • Python math library | isnan() method
    Python has math library and has many functions regarding it. One such function is isnan(). This method is used to check whether a given parameter is a valid number or not. Syntax : math.isnan(x) Parameters : x [Required] : It is any valid python data type or any number. Returns: Return type is boole
    1 min read
  • Python math library | isfinite() and remainder() method
    Python has math library and has many functions regarding to it. math.remainder() method returns an exact (floating) value as a remainder. Syntax: math.remainder(x, y) Time Complexity: O(1) Auxiliary space: O(1) For finite x and finite nonzero y, this is the difference x - n*y, where n is the closest
    1 min read
  • Python | os.closerange() method
    OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.closerange() method in Python is used to close all file descriptors in the ran
    2 min read
  • Python | os.close() method
    OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.close() method in Python is used to close the given file descriptor, so that i
    2 min read
  • Python | numpy.assert_allclose() method
    With the help of numpy.assert_allclose() method, we can get the assertion errors when two array objects are not equal upto the mark by using numpy.assert_allclose(). Syntax : numpy.assert_allclose(actual_array, desired_array) Return : Return the Assertion error if two array objects are not equal. Ex
    1 min read
  • Python __len__() magic method
    Python __len__ is one of the various magic methods in Python programming language, it is basically used to implement the len() function in Python because whenever we call the len() function then internally __len__ magic method is called. It finally returns an integer value that is greater than or eq
    2 min read
  • Python | Decimal compare() method
    Decimal#compare() : compare() is a Decimal class method which compares the two Decimal values. Syntax: Decimal.compare() Parameter: Decimal values Return: 1 - if a > b -1 - if a < b 0 - if a = b Code #1 : Example for compare() method # Python Program explaining # compare() method # loading dec
    2 min read
  • File flush() method in Python
    The flush() method in Python is used to quickly send data from the computer's temporary storage, known as a buffer, to a file or the screen. Normally, when you write something in Python, it doesn't get saved or shown right away. It stays in a buffer for a short time to make things faster. But someti
    3 min read
  • close() method in PyQt5
    In this article, we will see how to use close() method which belongs to the QWidget class, this method is used to close the window in PyQt5 application. In other words by close() method the window get closed without manually closing it. Syntax : self.close() Argument : It takes no argument. Code : #
    1 min read
  • Python String islower() Method
    The islower() method in Python checks if all characters in a string are lowercase. It returns True if all alphabetic characters are lowercase, otherwise, it returns False, if there is at least one uppercase letter. Let's look at a quick example of using the islower() method. [GFGTABS] Python s =
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences