NumPy hypot()

The hypot() function calculates the hypotenuse length given two arrays that represent the perpendicular sides of a right-angled triangle. Hypotenuse is the longest side of a right-angled triangle, opposite the right angle.

Example

import numpy as np

# create two arrays representing the perpendicular sides of right triangles
x1 = np.array([3, 4, 5])
x2 = np.array([4, 12, 13])

# calculate the hypotenuse using numpy.hypot() result = np.hypot(x1, x2)
print(result) # Output : [ 5. 13. 13.]

hypot() Syntax

The syntax of hypot() is:

numpy.round(x1, x2, out = None, where = True)

hypot() Arguments

The hypot() function takes one argument:

  • x1 - the first input array containing the values of one side of the right triangle
  • x2 - the second input array containing the values of the other side of the right triangle
  • out (optional) - the output array where the result will be stored
  • where (optional) - specifies a condition where the hypotenuse length is calculated

hypot() Return Value

The hypot() function returns a new array that contains the element-wise square root of the sum of the squares of the corresponding elements from two input arrays.


Example 1: Calculate Hypotenuse Length

import numpy as np

# create two 1D arrays representing the perpendicular sides of right triangles
side1 = np.array([4, 5, 8])
side2 = np.array([3, 12, 15])

# calculate the hypotenuse lengths using numpy.hypot() hypotenuse_lengths = np.hypot(side1, side2)
print("Hypotenuse lengths:") print(hypotenuse_lengths)

Output

Hypotenuse lengths:
[ 5.  13.  17.]

In this example, we have two 1D arrays side1 and side2 representing the perpendicular sides of right triangles.

The np.hypot() function calculates the hypotenuse length for each corresponding pair of elements from side1 and side2.

Mathematically,

numpy.hypot(4, 3) = sqrt((4^2) + (3^2)) = sqrt(16 + 9) = sqrt(25) = 5

This calculation represents the hypotenuse length for the first pair of elements (4, 3) in side1 and side2.

All the remaining pairs are calculated in the same way.


Example 2: Use of Optional out and where Argument in hypot()

import numpy as np

# create two arrays representing the perpendicular sides of right triangles
side1 = np.array([4, 5, 8])
side2 = np.array([3, 12, 15])

# create an empty array to store the hypotenuse lengths
result = np.zeros_like(side1, dtype=float)

# calculate the hypotenuse lengths using numpy.hypot() and # store the results in the 'result' array np.hypot(side1, side2, out=result, where=(side1 > 4))
print("Hypotenuse lengths:") print(result)

Output

Hypotenuse lengths:
[ 0. 13. 17.]

Here,

  • out=result specifies that the output of the np.hypot() function should be stored in the result array.
  • where=(side1 > 4) specifies that the calculation of the hypotenuse lengths will be performed only for the elements in side1 that are greater than 4.