Scala Tutorial Scala References

Scala - Math atan2() Method



The Scala Math atan2() method returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta). The returned value will be in the range -𝜋 through 𝜋. In special cases it returns the following:

  • If either argument is NaN, then the result is NaN.
  • If both arguments are positive infinity, then the result is closest to 𝜋/4.
  • If the first argument is positive or negative finite and the second argument is positive infinity, then the result is zero.
  • If the first argument is positive and finite and the second argument is negative infinity, then the result is closest to 𝜋.
  • If the first argument is negative and finite and the second argument is negative infinity, then the result is closest to -𝜋.
  • If the first argument is positive and the second argument is zero, or the first argument is positive infinity and the second argument is finite, then the result is closest to 𝜋/2.
  • If the first argument is negative and the second argument is zero, or the first argument is negative infinity and the second argument is finite, then the result is closest to -𝜋/2.
  • If the first argument is positive infinity and the second argument is negative infinity, then the result is closest to 3*𝜋/4.
  • If the first argument is negative infinity and the second argument is positive infinity, then the result is closest to -𝜋/4.
  • If both arguments are negative infinity, then the result is closest to -3*𝜋/4.

Syntax

def atan2(y: Double, x: Double): Double = java.lang.Math.atan2(y, x)

Parameters

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.

Exception

NA.

Example:

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

import scala.math._

object MainObject {
  def main(args: Array[String]) {
    println(s"atan2(10, 10) = ${atan2(10, 10)}"); 
    println(s"atan2(10, 20) = ${atan2(10, 20)}"); 
    println(s"atan2(-10, 20) = ${atan2(-10, 20)}");  
    println(s"atan2(10, Double.NaN) = ${atan2(10, Double.NaN)}"); 
    println("atan2(10, Double.PositiveInfinity) = "
            + atan2(10, Double.PositiveInfinity)); 
    println("atan2(Double.PositiveInfinity, 10) = "
            + atan2(Double.PositiveInfinity, 10));             
  }
}

The output of the above code will be:

atan2(10, 10) = 0.7853981633974483
atan2(10, 20) = 0.4636476090008061
atan2(-10, 20) = -0.4636476090008061
atan2(10, Double.NaN) = NaN
atan2(10, Double.PositiveInfinity) = 0.0
atan2(Double.PositiveInfinity, 10) = 1.5707963267948966

❮ Scala - Math Methods