github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/runtime/complex.go (about)

     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 runtime
     6  
     7  // inf2one returns a signed 1 if f is an infinity and a signed 0 otherwise.
     8  // The sign of the result is the sign of f.
     9  func inf2one(f float64) float64 {
    10  	g := 0.0
    11  	if isInf(f) {
    12  		g = 1.0
    13  	}
    14  	return copysign(g, f)
    15  }
    16  
    17  func complex64div(n complex64, m complex64) complex64 {
    18  	return complex64(complex128div(complex128(n), complex128(m)))
    19  }
    20  
    21  func complex128div(n complex128, m complex128) complex128 {
    22  	var e, f float64 // complex(e, f) = n/m
    23  
    24  	// Algorithm for robust complex division as described in
    25  	// Robert L. Smith: Algorithm 116: Complex division. Commun. ACM 5(8): 435 (1962).
    26  	if abs(real(m)) >= abs(imag(m)) {
    27  		ratio := imag(m) / real(m)
    28  		denom := real(m) + ratio*imag(m)
    29  		e = (real(n) + imag(n)*ratio) / denom
    30  		f = (imag(n) - real(n)*ratio) / denom
    31  	} else {
    32  		ratio := real(m) / imag(m)
    33  		denom := imag(m) + ratio*real(m)
    34  		e = (real(n)*ratio + imag(n)) / denom
    35  		f = (imag(n)*ratio - real(n)) / denom
    36  	}
    37  
    38  	if isNaN(e) && isNaN(f) {
    39  		// Correct final result to infinities and zeros if applicable.
    40  		// Matches C99: ISO/IEC 9899:1999 - G.5.1  Multiplicative operators.
    41  
    42  		a, b := real(n), imag(n)
    43  		c, d := real(m), imag(m)
    44  
    45  		switch {
    46  		case m == 0 && (!isNaN(a) || !isNaN(b)):
    47  			e = copysign(inf, c) * a
    48  			f = copysign(inf, c) * b
    49  
    50  		case (isInf(a) || isInf(b)) && isFinite(c) && isFinite(d):
    51  			a = inf2one(a)
    52  			b = inf2one(b)
    53  			e = inf * (a*c + b*d)
    54  			f = inf * (b*c - a*d)
    55  
    56  		case (isInf(c) || isInf(d)) && isFinite(a) && isFinite(b):
    57  			c = inf2one(c)
    58  			d = inf2one(d)
    59  			e = 0 * (a*c + b*d)
    60  			f = 0 * (b*c - a*d)
    61  		}
    62  	}
    63  
    64  	return complex(e, f)
    65  }