Swift Tutorial Swift Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Swift - atan2() Function

The Swift atan2() function returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta). The return value will be in the range -𝜋 through 𝜋.


In Foundation framework, it is defined as follows:

public func atan2(_ __y: Double, _ __x: Double) -> Double


y Specify the ordinate coordinate.
x Specify the abscissa coordinate.

Return Value

Returns theta of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.


In the example below, atan2() function is used to calculate the theta of a point.

import Foundation

print("atan2(1.0, 1.0) = \(atan2(1.0, 1.0))")
print("atan2(1.0, 2.0) = \(atan2(1.0, 2.0))")
print("atan2(2.0, 1.0) = \(atan2(2.0, 1.0))")
print("atan2(-1.0, 2.0) = \(atan2(-1.0, 2.0))")
print("atan2(-1.0, -2.0) = \(atan2(-1.0, -2.0))")

The output of the above code will be:

atan2(1.0, 1.0) = 0.7853981633974483
atan2(1.0, 2.0) = 0.4636476090008061
atan2(2.0, 1.0) = 1.1071487177940904
atan2(-1.0, 2.0) = -0.4636476090008061
atan2(-1.0, -2.0) = -2.677945044588987

❮ Swift Math Functions