What is the hypot() function in Swift?

Overview

The longest side of a right-angle triangle, and the side opposite to the right angle, is known as the hypotenuse in geometry.

The mathematical formula to calculate the hypotenuse’s length is known as the Pythagorean theorem and is as follows:

hypotenuse = sqrt( length^2 + base^2 )

The following figure shows the visual representation of the hypot() function:

A visual representation of the hypot() function

Note: We need to import Foundation in our code to use the hypot() function. We can import it using import Foundation.

Syntax

hypot(length, base)

Parameters

This function requires the length and base as parameters.

Return value

This function returns the hypotenuse of the right-angle triangle. The triangle’s length and base are passed as parameters.

Example

The code below shows the use of the hypot() function in Swift:

import Swift
import Foundation
//positive: length positive: base
print ("The value of hypot(2.0,3.0) : ",hypot(2.0,3.0));
//positive: length negative: base
print ("The value of hypot(0.25,-2.0) : ",hypot(0.25,-2.0));
//negative: length positive: base
print ("The value of hypot(-10.0,2.0) : ",hypot(-10.0,2.0));
//negative: length negative: base
print ("The value of hypot(-0.5,-1.0) : ",hypot(-0.5,-1.0));

Explanation

  • Line 2: We add the Foundation header required for hypot() function.
  • Line 5: We calculate the hypotenuse of the positive length and the positive base using hypot().
  • Line 8: We calculate the hypotenuse of the positive length and the negative base using hypot().
  • Line 11: We calculate the hypotenuse of the negative length and the positive base using hypot().
  • Line 14: We calculate the hypotenuse of the negative length and the negative base using hypot().