hypot() function Python (original) (raw)

Last Updated : 19 Feb, 2025

math.hypot() function in Python is used to compute the Euclidean distance from the origin (0, 0) to a point (x, y) in a 2D plane. It calculates the hypotenuse of a right triangle, given the lengths of the two other sides.

**Example

Python `

import math

x = 3 y = 4

res = math.hypot(x, y) print(res)

`

**Explanation:

In this example, the two sides of the right triangle are 3 and 4. The hypot() function calculates the hypotenuse as:

\sqrt{3^2 + 4^2} = \sqrt{9 + 16} = \sqrt{25} = 5.0

Thus, the output is 5.0, which is the length of the hypotenuse.

Syntax of hypot() method

math.hypot(x, y)

**Parameters

**Return Type

**Error

**Note : One has to import math module before using **hypot() function.

Examples of hypot() method

**1. Basic Hypotenuse Calculation

This example demonstrates how the hypot() function works with positive and negative values to compute the hypotenuse.

Python `

import math

Use of hypot function

print("hypot(3, 4) : ", math.hypot(3, 4))

Neglects the negative sign

print("hypot(-3, 4) : ", math.hypot(-3, 4))

print("hypot(6, 6) : ", math.hypot(6, 6))

`

Output

hypot(3, 4) : 5.0 hypot(-3, 4) : 5.0 hypot(6, 6) : 8.48528137423857

**Explanation

2. Error Handling in hypot()

This example shows an error when an incorrect number of arguments is passed to the hypot() function (more than two arguments).

Python `

import math

Use of hypot() function with incorrect number of arguments

try: print("hypot(3, 4, 6) : ", math.hypot(3, 4, 6))

except TypeError as e: print("Error:", e)

`

Output

hypot(3, 4, 6) : 7.810249675906654

**Explanation

**3. Hypotenuse Calculation Using Perpendicular and Base

**Practical Application : Given perpendicular and base of a right angle triangle find the hypotenuse. Using Pythagorean theorem which states that the square of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the other two sides.

This example demonstrates how to use the hypot() function to calculate the hypotenuse of a right triangle given the perpendicular and base.

Python `

from math import hypot

Perpendicular and base

p = 3 b = 4

Calculates the hypotenuse

print(hypot(p, b))

`

**Explanation