| by Arround The Web | No comments

NumPy np.gcd()

We all remember GCD or Greatest Common Divisor in Elementary Mathematics. However, in this tutorial, we will learn how to simplify the manual GCD calculation using a simple function in NumPy.

Let us take back our time.

Function Syntax

GCD or Greatest Common Divisor is the greatest positive value that can divide two or more numbers.

The gcd function in NumPy has a syntax as shown:

numpy.gcd(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'gcd'>

Despite the crazy-looking syntax, you only need to worry about two parameters, as shown:

  1. x1 and x2 – refer to the input arrays.

Example #1

The code below shows using the gcd() function with two scalar values.

# import numpy
import numpy as np
print(f"gcd: {np.gcd(130, 13)}")

The above code should return the GCD of 130 and 13 as shown:

gcd: 13

Example #2

To get the GCD of two arrays, we can do:

arr_1 = np.array([11,12,13])
arr_2 = np.array([14,145,15])
print(f"gcd: {np.gcd(arr_1, arr_2)}")

The code above should return:

gcd: [1 1 1]

Example #3

You can also determine the GCD of an element of arrays and a scalar value. For example:

arr = np.array([14,145,15])
print(f"GCD: {np.gcd(arr, 5)}")

The example code above should return the GCD of the array, and 5.

GCD: [1 5 5]

Closing

This tutorial walks through how to calculate the GCD of array elements along a given axis.

Thanks for reading!!

Share Button

Source: linuxhint.com

Leave a Reply