Source file src/math/sincos.go

     1  // Copyright 2010 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  // Coefficients _sin[] and _cos[] are found in pkg/math/sin.go.
     8  
     9  // Sincos returns Sin(x), Cos(x).
    10  //
    11  // Special cases are:
    12  //
    13  //	Sincos(±0) = ±0, 1
    14  //	Sincos(±Inf) = NaN, NaN
    15  //	Sincos(NaN) = NaN, NaN
    16  func Sincos(x float64) (sin, cos float64) {
    17  	const (
    18  		PI4A = 7.85398125648498535156e-1  // 0x3fe921fb40000000, Pi/4 split into three parts
    19  		PI4B = 3.77489470793079817668e-8  // 0x3e64442d00000000,
    20  		PI4C = 2.69515142907905952645e-15 // 0x3ce8469898cc5170,
    21  	)
    22  	// special cases
    23  	switch {
    24  	case x == 0:
    25  		return x, 1 // return ±0.0, 1.0
    26  	case IsNaN(x) || IsInf(x, 0):
    27  		return NaN(), NaN()
    28  	}
    29  
    30  	// make argument positive
    31  	sinSign, cosSign := false, false
    32  	if x < 0 {
    33  		x = -x
    34  		sinSign = true
    35  	}
    36  
    37  	var j uint64
    38  	var y, z float64
    39  	if x >= reduceThreshold {
    40  		j, z = trigReduce(x)
    41  	} else {
    42  		j = uint64(x * (4 / Pi)) // integer part of x/(Pi/4), as integer for tests on the phase angle
    43  		y = float64(j)           // integer part of x/(Pi/4), as float
    44  
    45  		if j&1 == 1 { // map zeros to origin
    46  			j++
    47  			y++
    48  		}
    49  		j &= 7                               // octant modulo 2Pi radians (360 degrees)
    50  		z = ((x - y*PI4A) - y*PI4B) - y*PI4C // Extended precision modular arithmetic
    51  	}
    52  	if j > 3 { // reflect in x axis
    53  		j -= 4
    54  		sinSign, cosSign = !sinSign, !cosSign
    55  	}
    56  	if j > 1 {
    57  		cosSign = !cosSign
    58  	}
    59  
    60  	zz := z * z
    61  	cos = 1.0 - 0.5*zz + zz*zz*((((((_cos[0]*zz)+_cos[1])*zz+_cos[2])*zz+_cos[3])*zz+_cos[4])*zz+_cos[5])
    62  	sin = z + z*zz*((((((_sin[0]*zz)+_sin[1])*zz+_sin[2])*zz+_sin[3])*zz+_sin[4])*zz+_sin[5])
    63  	if j == 1 || j == 2 {
    64  		sin, cos = cos, sin
    65  	}
    66  	if cosSign {
    67  		cos = -cos
    68  	}
    69  	if sinSign {
    70  		sin = -sin
    71  	}
    72  	return
    73  }
    74  

View as plain text