# Source file src/runtime/complex.go

```     1  // Copyright 2010 The Go Authors. All rights reserved.
2  // Use of this source code is governed by a BSD-style
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 complex128div(n complex128, m complex128) complex128 {
18  	var e, f float64 // complex(e, f) = n/m
19
20  	// Algorithm for robust complex division as described in
21  	// Robert L. Smith: Algorithm 116: Complex division. Commun. ACM 5(8): 435 (1962).
22  	if abs(real(m)) >= abs(imag(m)) {
23  		ratio := imag(m) / real(m)
24  		denom := real(m) + ratio*imag(m)
25  		e = (real(n) + imag(n)*ratio) / denom
26  		f = (imag(n) - real(n)*ratio) / denom
27  	} else {
28  		ratio := real(m) / imag(m)
29  		denom := imag(m) + ratio*real(m)
30  		e = (real(n)*ratio + imag(n)) / denom
31  		f = (imag(n)*ratio - real(n)) / denom
32  	}
33
34  	if isNaN(e) && isNaN(f) {
35  		// Correct final result to infinities and zeros if applicable.
36  		// Matches C99: ISO/IEC 9899:1999 - G.5.1  Multiplicative operators.
37
38  		a, b := real(n), imag(n)
39  		c, d := real(m), imag(m)
40
41  		switch {
42  		case m == 0 && (!isNaN(a) || !isNaN(b)):
43  			e = copysign(inf, c) * a
44  			f = copysign(inf, c) * b
45
46  		case (isInf(a) || isInf(b)) && isFinite(c) && isFinite(d):
47  			a = inf2one(a)
48  			b = inf2one(b)
49  			e = inf * (a*c + b*d)
50  			f = inf * (b*c - a*d)
51
52  		case (isInf(c) || isInf(d)) && isFinite(a) && isFinite(b):
53  			c = inf2one(c)
54  			d = inf2one(d)
55  			e = 0 * (a*c + b*d)
56  			f = 0 * (b*c - a*d)
57  		}
58  	}
59
60  	return complex(e, f)
61  }
62
```

View as plain text