github.com/primecitizens/pcz/std@v0.2.1/builtin/complex/complex128.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright 2023 The Prime Citizens
     3  //
     4  // Copyright 2010 The Go Authors. All rights reserved.
     5  // Use of this source code is governed by a BSD-style
     6  // license that can be found in the LICENSE file.
     7  
     8  package stdcomplex
     9  
    10  import (
    11  	stdfloat "github.com/primecitizens/pcz/std/builtin/float"
    12  )
    13  
    14  func Complex128Div(n, m complex128) complex128 {
    15  	var e, f float64 // complex(e, f) = n/m
    16  
    17  	// Algorithm for robust complex division as described in
    18  	// Robert L. Smith: Algorithm 116: Complex division. Commun. ACM 5(8): 435 (1962).
    19  	if stdfloat.Abs(real(m)) >= stdfloat.Abs(imag(m)) {
    20  		ratio := imag(m) / real(m)
    21  		denom := real(m) + ratio*imag(m)
    22  		e = (real(n) + imag(n)*ratio) / denom
    23  		f = (imag(n) - real(n)*ratio) / denom
    24  	} else {
    25  		ratio := real(m) / imag(m)
    26  		denom := imag(m) + ratio*real(m)
    27  		e = (real(n)*ratio + imag(n)) / denom
    28  		f = (imag(n)*ratio - real(n)) / denom
    29  	}
    30  
    31  	if stdfloat.IsNaN(e) && stdfloat.IsNaN(f) {
    32  		// Correct final result to infinities and zeros if applicable.
    33  		// Matches C99: ISO/IEC 9899:1999 - G.5.1  Multiplicative operators.
    34  
    35  		a, b := real(n), imag(n)
    36  		c, d := real(m), imag(m)
    37  
    38  		switch {
    39  		case m == 0 && (!stdfloat.IsNaN(a) || !stdfloat.IsNaN(b)):
    40  			e = stdfloat.CopySign(inf, c) * a
    41  			f = stdfloat.CopySign(inf, c) * b
    42  
    43  		case (stdfloat.IsInf(a) || stdfloat.IsInf(b)) && stdfloat.IsFinite(c) && stdfloat.IsFinite(d):
    44  			a = inf2one(a)
    45  			b = inf2one(b)
    46  			e = inf * (a*c + b*d)
    47  			f = inf * (b*c - a*d)
    48  
    49  		case (stdfloat.IsInf(c) || stdfloat.IsInf(d)) && stdfloat.IsFinite(a) && stdfloat.IsFinite(b):
    50  			c = inf2one(c)
    51  			d = inf2one(d)
    52  			e = 0 * (a*c + b*d)
    53  			f = 0 * (b*c - a*d)
    54  		}
    55  	}
    56  
    57  	return complex(e, f)
    58  }
    59  
    60  // inf2one returns a signed 1 if f is an infinity and a signed 0 otherwise.
    61  // The sign of the result is the sign of f.
    62  func inf2one(f float64) float64 {
    63  	g := 0.0
    64  	if stdfloat.IsInf(f) {
    65  		g = 1.0
    66  	}
    67  	return stdfloat.CopySign(g, f)
    68  }