Source file src/math/atan2.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package math
     6  
     7  // Atan2 returns the arc tangent of y/x, using
     8  // the signs of the two to determine the quadrant
     9  // of the return value.
    10  //
    11  // Special cases are (in order):
    12  //
    13  //	Atan2(y, NaN) = NaN
    14  //	Atan2(NaN, x) = NaN
    15  //	Atan2(+0, x>=0) = +0
    16  //	Atan2(-0, x>=0) = -0
    17  //	Atan2(+0, x<=-0) = +Pi
    18  //	Atan2(-0, x<=-0) = -Pi
    19  //	Atan2(y>0, 0) = +Pi/2
    20  //	Atan2(y<0, 0) = -Pi/2
    21  //	Atan2(+Inf, +Inf) = +Pi/4
    22  //	Atan2(-Inf, +Inf) = -Pi/4
    23  //	Atan2(+Inf, -Inf) = 3Pi/4
    24  //	Atan2(-Inf, -Inf) = -3Pi/4
    25  //	Atan2(y, +Inf) = 0
    26  //	Atan2(y>0, -Inf) = +Pi
    27  //	Atan2(y<0, -Inf) = -Pi
    28  //	Atan2(+Inf, x) = +Pi/2
    29  //	Atan2(-Inf, x) = -Pi/2
    30  func Atan2(y, x float64) float64 {
    31  	if haveArchAtan2 {
    32  		return archAtan2(y, x)
    33  	}
    34  	return atan2(y, x)
    35  }
    36  
    37  func atan2(y, x float64) float64 {
    38  	// special cases
    39  	switch {
    40  	case IsNaN(y) || IsNaN(x):
    41  		return NaN()
    42  	case y == 0:
    43  		if x >= 0 && !Signbit(x) {
    44  			return Copysign(0, y)
    45  		}
    46  		return Copysign(Pi, y)
    47  	case x == 0:
    48  		return Copysign(Pi/2, y)
    49  	case IsInf(x, 0):
    50  		if IsInf(x, 1) {
    51  			switch {
    52  			case IsInf(y, 0):
    53  				return Copysign(Pi/4, y)
    54  			default:
    55  				return Copysign(0, y)
    56  			}
    57  		}
    58  		switch {
    59  		case IsInf(y, 0):
    60  			return Copysign(3*Pi/4, y)
    61  		default:
    62  			return Copysign(Pi, y)
    63  		}
    64  	case IsInf(y, 0):
    65  		return Copysign(Pi/2, y)
    66  	}
    67  
    68  	// Call atan and determine the quadrant.
    69  	q := Atan(y / x)
    70  	if x < 0 {
    71  		if q <= 0 {
    72  			return q + Pi
    73  		}
    74  		return q - Pi
    75  	}
    76  	return q
    77  }
    78  

View as plain text