• Skip to secondary menu
  • Skip to main content
  • Skip to primary sidebar

Python and R Tips

Learn Data Science with Python and R

  • Home
  • Python
  • Pandas
    • Pandas 101
  • tidyverse
    • tidyverse 101
  • R
  • Linux
  • About
    • Privacy Policy
You are here: Home / Python / Python Tips / Numpy isclose() function with examples

Numpy isclose() function with examples

December 24, 2022 by cmdlinetips

This post covers numpy.isclose(), the standard function for comparing floating-point values in Python.

Why not use ==?

  • Floating-Point Inaccuracy: Computers cannot represent most decimal fractions exactly in binary, leading to small precision errors. A direct comparison with == will often fail when numbers are mathematically equal but have tiny representational differences.
  • The Solution: numpy.isclose() circumvents this by checking if two values lie within a defined tolerance of each other, providing a much more practical and reliable comparison.

Core Uses of numpy.isclose()

  • Scalar Comparison: Safely check if two individual floating-point numbers are effectively equal.
  • Array Comparison: Perform an element-wise comparison between two NumPy arrays. This is crucial for verifying results in numerical computations where visual inspection is impractical and unreliable.

Let us started on learning how to use Numpy’s isclose() function. Let us load numpy and check Numpy’s version.

import numpy as np
np.<strong>version</strong>
1.24.0

Numpy isclose() function to check if numbers or arrays are equal

Understanding the numpy.isclose() Syntax

The basic syntax for the numpy.isclose() function provides fine-grained control over the comparison.

Function Signature:

numpy.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)

Parameters Explained:

  • a, b: The input arrays or scalars to be compared.
  • rtol (relative tolerance): This is a relative tolerance that scales with the magnitude of the input b. The default 1e-05 is useful for most cases. It becomes more important than atol for large numbers.
  • atol (absolute tolerance): This is a minimum, absolute tolerance. It’s a fixed value that is most useful for comparisons where one of the numbers is close to zero. The default is 1e-08.
  • equal_nan: If set to True, the function will consider NaN (Not a Number) values in the same positions of the arrays as equal. By default, it is False.

The Underlying Formula

The function returns True for a pair of values a and b if their difference satisfies the following mathematical equation:

\text{absolute}(a - b) \le (\text{atol} + \text{rtol} \cdot \text{absolute}(b))

This formula effectively checks if the difference is within a margin of error that combines a fixed value (atol) and a percentage of the input value (rtol).

Numpy isclose() function: Check if two numbers are the same

Int he first example of Numpy’s isclose() fucntion, we check if two numbers are close enough. Let us say we have two numbers a and b

a = 1
b = 1.1

If we use Numpy’s isclose() to find if they are close enough, we will get False as result. This is because the relative difference between the two numbers is bigger than the default tolerance 1e-05.

np.isclose(a,b)

False

Now let us consider another two numbers as shown below

a = 1
b = 1.00001

Here we can see that the difference is equal to the relative tolerance level. Therefore, we would get True when we use np.close() function.

np.isclose(a,b)

True

We can change the tolerance level to force two numbers close when needed. In the example below we changed the relative tolerance level from default 1e-05 to 0.1. Now the two numbers

a = 1
b = 1.1

are close enough under the new tolerance level. And we will get True as result.

np.isclose(a, b, rtol=0.1)

True

Numpy isclose() function: Check if two arrays are the same

Now lets us consider two Numpy arrays and check if their elements are close to each other. We can use isclose as follows:

a = np.array([1, 2, 3])
b = np.array([1.01, 2.01, 3.01])

result = np.isclose(a, b)

When comparing arrays, Numpy’s isclose function returns an array of Boolean values, with each element indicating whether the corresponding element in a is close to the corresponding element in b.

In this case, we get boolean array containing three False as the relative difference between every element is bigger than the default tolerance value.

print(result)

[False False False]

Now let us consider the following two arrays and use Numpy’s np.close() with the default tolerance level.

a = np.array([1, 2, 3])
b = np.array([1.0000001, 2.00001, 3.01])

result = np.isclose(a, b)

print(result)

[ True  True False]

We got True for the first and second element as the difference is smaller than or equal to rtol value. And for the third element we got False is the difference is bigger than the default tolerance.

Another close relative of Numpy’s isclose() function is allclose() function. See this post to learn about how to use allcose() function.

  • Numpy allclose() function with examples
  • Share this:

    • Share on Facebook (Opens in new window) Facebook
    • Share on X (Opens in new window) X

    Filed Under: Python, Python Tips Tagged With: Numpy isclose() function

    Reader Interactions

    Trackbacks

    1. Cholesky Decomposition - Python and R Tips says:
      December 27, 2022 at 10:46 pm

      […] can further verify that by using Numpy’s np.isclose() function to find if each element of the original matrix is close to the reconstructed matrix from […]

    2. Numpy allclose() function with examples - Python and R Tips says:
      December 29, 2022 at 8:50 am

      […] function that is similar to allclose() is Numpy’s isclose() function. They both are similar in the sense that they try to find if two arrays are close by making […]

    Primary Sidebar

    Subscribe to Python and R Tips and Learn Data Science

    Learn Pandas in Python and Tidyverse in R

    Tags

    Altair Basic NumPy Book Review Data Science Data Science Books Data Science Resources Data Science Roundup Data Visualization Dimensionality Reduction Dropbox Dropbox Free Space Dropbox Tips Emacs Emacs Tips ggplot2 Linux Commands Linux Tips Mac Os X Tips Maximum Likelihood Estimation in R MLE in R NumPy Pandas Pandas 101 Pandas Dataframe Pandas Data Frame pandas groupby() Pandas select columns Pandas select_dtypes Python Python 3 Python Boxplot Python Tips R rstats R Tips Seaborn Seaborn Boxplot Seaborn Catplot Shell Scripting Sparse Matrix in Python tidy evaluation tidyverse tidyverse 101 Vim Vim Tips

    RSS RSS

    • How to convert row names to a column in Pandas
    • How to resize an image with PyTorch
    • Fashion-MNIST data from PyTorch
    • Pandas case_when() with multiple examples
    • An Introduction to Statistical Learning: with Applications in Python Is Here
    • 10 Tips to customize ggplot2 title text
    • 8 Plot types with Matplotlib in Python
    • PCA on S&P 500 Stock Return Data
    • Linear Regression with Matrix Decomposition Methods
    • Numpy’s random choice() function

    Copyright © 2026 · Lifestyle Pro on Genesis Framework · WordPress · Log in

    Go to mobile version