Skip to content

Commit 884c192

Browse files
committed
Fix comparison of terms with non-comparable coefficients
1 parent 905ee7c commit 884c192

File tree

2 files changed

+49
-4
lines changed

2 files changed

+49
-4
lines changed

src/operators.jl

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,24 @@
33
Base.@pure Base.isless(v1::AbstractVariable, v2::AbstractVariable) = name(v1) > name(v2)
44
Base.isless(m1::AbstractTermLike, m2::AbstractTermLike) = isless(promote(m1, m2)...)
55

6+
# Implement this to make coefficients be compared with terms.
7+
function isless_coefficient(a::Real, b::Real)
8+
return a < b
9+
end
10+
function isless_coefficient(a::Number, b::Number)
11+
return abs(a) < abs(b)
12+
end
13+
# By default, coefficients are not comparable so `a` is not strictly
14+
# less than `b`, they are considered sort of equal.
15+
isless_coefficient(a, b) = false
16+
617
function Base.isless(t1::AbstractTerm, t2::AbstractTerm)
718
if monomial(t1) < monomial(t2)
8-
true
19+
return true
920
elseif monomial(t1) == monomial(t2)
10-
abs(coefficient(t1)) < abs(coefficient(t2))
21+
return isless_coefficient(coefficient(t1), coefficient(t2))
1122
else
12-
false
23+
return false
1324
end
1425
end
1526

test/term.jl

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
struct CoefNotComparable
2+
end
3+
Base.iszero(::CoefNotComparable) = false
4+
15
@testset "Term" begin
26
Mod.@polyvar x
37
@test convert(Any, 1x) == 1x
@@ -49,7 +53,6 @@
4953
@test_throws InexactError push!([1], 2x)
5054
@test_throws ErrorException push!([x^2], 2x)
5155

52-
5356
@testset "Effective variables" begin
5457
T = variable_union_type(x)
5558
@test x isa T
@@ -61,4 +64,35 @@
6164
@test T[y] == @inferred effective_variables(x^0 * y)
6265
@test T[y] == @inferred effective_variables(y * x^0)
6366
end
67+
68+
@testset "Compare terms" begin
69+
t1 = 1 * x
70+
t2 = 2 * x
71+
@test t1 < t2
72+
@test t1 <= t2
73+
@test !(t1 > t2)
74+
@test !(t1 >= t2)
75+
76+
t1 = (1 + 1im) * x
77+
t2 = (2 + 2im) * x
78+
@test t1 < t2
79+
@test t1 <= t2
80+
@test !(t1 > t2)
81+
@test !(t1 >= t2)
82+
83+
a = CoefNotComparable()
84+
b = CoefNotComparable()
85+
t1 = a * x
86+
t2 = b * y
87+
@test t1 > t2
88+
@test t1 >= t2
89+
@test !(t1 < t2)
90+
@test !(t1 <= t2)
91+
t1 = a * x
92+
t2 = b * x
93+
@test !(t1 > t2)
94+
@test t1 >= t2
95+
@test !(t1 < t2)
96+
@test t1 <= t2
97+
end
6498
end

0 commit comments

Comments
 (0)