Skip to content

Commit bfe17ce

Browse files
lbenetdpsanders
authored andcommitted
Add specialized arithmetic methods for Interval{T} and T (#125)
1 parent 0897d41 commit bfe17ce

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

src/intervals/arithmetic.jl

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,21 @@ typemax(::Type{Interval{T}}) where T<:Integer = Interval(typemax(T))
6565
+(a::Interval) = a
6666
-(a::Interval) = Interval(-a.hi, -a.lo)
6767

68+
function +(a::Interval{T}, b::T) where {T<:Real}
69+
isempty(a) && return emptyinterval(T)
70+
@round(a.lo + b, a.hi + b)
71+
end
72+
+(b::T, a::Interval{T}) where {T<:Real} = a+b
73+
74+
function -(a::Interval{T}, b::T) where {T<:Real}
75+
isempty(a) && return emptyinterval(T)
76+
@round(a.lo - b, a.hi - b)
77+
end
78+
function -(b::T, a::Interval{T}) where {T<:Real}
79+
isempty(a) && return emptyinterval(T)
80+
@round(b - a.lo, b - a.hi)
81+
end
82+
6883
function +(a::Interval{T}, b::Interval{T}) where T<:Real
6984
(isempty(a) || isempty(b)) && return emptyinterval(T)
7085
@round(a.lo + b.lo, a.hi + b.hi)
@@ -77,6 +92,17 @@ end
7792

7893

7994
## Multiplication
95+
function *(x::T, a::Interval{T}) where {T<:Real}
96+
isempty(a) && return emptyinterval(T)
97+
(iszero(a) || iszero(x)) && return zero(Interval{T})
98+
99+
if x 0.0
100+
return @round(a.lo*x, a.hi*x)
101+
else
102+
return @round(a.hi*x, a.lo*x)
103+
end
104+
end
105+
*(a::Interval{T}, x::T) where {T<:Real} = x*a
80106

81107
function *(a::Interval{T}, b::Interval{T}) where T<:Real
82108
(isempty(a) || isempty(b)) && return emptyinterval(T)
@@ -100,6 +126,17 @@ end
100126

101127

102128
## Division
129+
function /(a::Interval{T}, x::T) where {T<:Real}
130+
isempty(a) && return emptyinterval(T)
131+
iszero(x) && return emptyinterval(T)
132+
iszero(a) && return zero(Interval{T})
133+
134+
if x 0.0
135+
return @round(a.lo/x, a.hi/x)
136+
else
137+
return @round(a.hi/x, a.lo/x)
138+
end
139+
end
103140

104141
function inv(a::Interval{T}) where T<:Real
105142
isempty(a) && return emptyinterval(a)

src/intervals/rounding.jl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ struct IntervalRounding{T} end
3131

3232
# Functions that are the same for all rounding types:
3333
@eval begin
34-
# unary minus:
34+
# unary plus and minus:
35+
+(a::T, ::RoundingMode) where {T<:AbstractFloat} = a # ignore rounding
3536
-(a::T, ::RoundingMode) where {T<:AbstractFloat} = -a # ignore rounding
3637

3738
# zero:

0 commit comments

Comments
 (0)