Skip to content

Commit 8144c2f

Browse files
committed
Define some complex overloads
1 parent 2f92933 commit 8144c2f

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/ModelingToolkit.jl

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,39 @@ SymbolicUtils.@number_methods(Num,
6161
Num(f(value(a))),
6262
Num(f(value(a), value(b))))
6363

64+
for C in [Complex, Complex{Bool}]
65+
@eval begin
66+
Base.:*(x::Num, z::$C) = Complex(x * real(z), x * imag(z))
67+
Base.:*(z::$C, x::Num) = Complex(real(z) * x, imag(z) * x)
68+
end
69+
end
70+
71+
Base.:+(x::Num, z::Complex) = Complex(x + real(z), imag(z))
72+
Base.:+(z::Complex, x::Num) = Complex(real(z) + x, imag(z))
73+
Base.:-(x::Num, z::Complex) = Complex(x - real(z), -imag(z))
74+
Base.:-(z::Complex, x::Num) = Complex(real(z) - x, imag(z))
75+
76+
function Base.inv(z::Complex{Num})
77+
a, b = reim(z)
78+
den = a^2 + b^2
79+
Complex(a/den, -b/den)
80+
end
81+
function Base.:/(x::Complex{Num}, y::Complex{Num})
82+
a, b = reim(x)
83+
c, d = reim(y)
84+
den = c^2 + d^2
85+
Complex((a*c + b*d)/den, (b*c - a*d)/den)
86+
end
87+
88+
function Base.show(io::IO, z::Complex{<:Num})
89+
r, i = reim(z)
90+
compact = get(io, :compact, false)
91+
show(io, r)
92+
print(io, compact ? "+" : " + ")
93+
show(io, i)
94+
print(io, "*im")
95+
end
96+
6497
SymbolicUtils.simplify(n::Num; kw...) = Num(SymbolicUtils.simplify(value(n); kw...))
6598

6699
SymbolicUtils.symtype(n::Num) = symtype(n.val)

test/operation_overloads.jl

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,3 +113,19 @@ A = [1 1 1
113113
1 1 1]
114114
@test _det1(A) == 0
115115
@test _det2(A) == 0
116+
117+
@variables a b c d
118+
z1 = a + b * im
119+
z2 = c + d * im
120+
@test z1 * 2 - Complex(2a, 2b) == 0
121+
@test isequal(2z1, Complex(2a, 2b))
122+
@test isequal(z1 / z1, 1)
123+
@test isequal(z1 / z2, Complex((a*c + b*d)/(c^2 + d^2), (b*c - a*d)/(c^2 + d^2)))
124+
@test isequal(1 / z2, Complex(c/(c^2 + d^2), -d/(c^2 + d^2)))
125+
@test isequal(z1 * z2, Complex(a*c - b*d, a*d + b*c))
126+
@test isequal(z1 - z2, Complex(a - c, b - d))
127+
@test isequal(z1 + z2, Complex(a + c, b + d))
128+
@test isequal(z1 + 2, Complex(a + 2, b))
129+
@test isequal(2 + z1, Complex(2 + a, b))
130+
@test isequal(z1 - 2, Complex(a - 2, b))
131+
@test isequal(2 - z1, Complex(2 - a, -b))

0 commit comments

Comments
 (0)