What is the tan() function in Swift?

Overview

In Swift, the tan() function is used to return the tangent of a number. The mathematical representation of the tan() function is shown below.

tan(x)=Length of the opposite sideLength of the adjacent sidetan(x)=\frac{Length \space of \space the \space opposite \space side}{Length \space of \space the \space adjacent \space side}

Note: We need to import Foundation in our code to use the tan() function. We can import it like this: import Foundation.

Syntax

//number can be real, float, or double.
tan(number)

Parameter

This function takes the parameter, number, which can be a real, float, or double value representing an angle in radians.

Formula

In order to convert degrees to radians, use the following formula:

radians=degrees(pi/180)radians = degrees * ( pi / 180 )

Return value

This function returns the tangent of the number that is sent as a parameter.

Example

import Swift
import Foundation
//positive number in radians
print("The value of tan(2.3) :", tan(2.3));
// negative number in radians
print("The value of tan(-2.3) :", tan(-2.3));
//converting the degrees angle into radians and then applying tan()
// degrees = 45.0
// PI = 3.14159265
print("The value of tan(45.0 * (PI / 180.0)) :", tan(45.0 * (Double.pi / 180.0)));

Explanation

  • Line 2: We add the Foundation header required for tan() function.
  • Line 5: We use the tan() function to calculate the tangent of the positive number in radians.
  • Line 8: We use the tan() function to calculate the tangent of the negative number in radians.
  • Line 13: We use the tan() function to convert the angle in degrees to radians. Next, we use tan() to find its tangent.

Free Resources