d: Merge upstream dmd, druntime 4c18eed967, phobos d945686a4.
[official-gcc.git] / gcc / d / dmd / root / complex.d
blob57d1e340eff142028eb19195a7b01cbca9fa245e
1 /**
2 * Implements a complex number type.
4 * Copyright: Copyright (C) 1999-2023 by The D Language Foundation, All Rights Reserved
5 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
6 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/root/complex.d, _complex.d)
8 * Documentation: https://dlang.org/phobos/dmd_root_complex.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/root/complex.d
12 module dmd.root.complex;
14 import dmd.root.ctfloat;
16 nothrow:
18 extern (C++) struct complex_t
20 real_t re;
21 real_t im;
23 nothrow:
25 this() @disable;
27 this(real_t re)
29 this(re, CTFloat.zero);
32 this(real_t re, real_t im) @safe
34 this.re = re;
35 this.im = im;
38 extern (D) complex_t opBinary(string op)(complex_t y)
39 if (op == "+")
41 return complex_t(re + y.re, im + y.im);
44 extern (D) complex_t opBinary(string op)(complex_t y)
45 if (op == "-")
47 return complex_t(re - y.re, im - y.im);
50 extern (D) complex_t opUnary(string op)()
51 if (op == "-")
53 return complex_t(-re, -im);
56 extern (D) complex_t opBinary(string op)(complex_t y)
57 if (op == "*")
59 return complex_t(re * y.re - im * y.im, im * y.re + re * y.im);
62 extern (D) complex_t opBinaryRight(string op)(real_t x)
63 if (op == "*")
65 return complex_t(x) * this;
68 extern (D) complex_t opBinary(string op)(real_t y)
69 if (op == "*")
71 return this * complex_t(y);
74 extern (D) complex_t opBinary(string op)(real_t y)
75 if (op == "/")
77 return this / complex_t(y);
80 extern (D) complex_t opBinary(string op)(complex_t y)
81 if (op == "/")
83 if (CTFloat.fabs(y.re) < CTFloat.fabs(y.im))
85 const r = y.re / y.im;
86 const den = y.im + r * y.re;
87 return complex_t((re * r + im) / den, (im * r - re) / den);
89 else
91 const r = y.im / y.re;
92 const den = y.re + r * y.im;
93 return complex_t((re + r * im) / den, (im - r * re) / den);
97 extern (D) bool opCast(T : bool)() const
99 return re || im;
102 int opEquals(complex_t y) const @safe
104 return re == y.re && im == y.im;
108 extern (C++) real_t creall(complex_t x) @safe
110 return x.re;
113 extern (C++) real_t cimagl(complex_t x) @safe
115 return x.im;