Skip to content

Commit ccc54d2

Browse files
authored
Merge pull request #95 from neveritt/master
Proper conversions in arithmetic with different element-types closes #94
2 parents aafe0c6 + 5590d4c commit ccc54d2

File tree

2 files changed

+18
-16
lines changed

2 files changed

+18
-16
lines changed

src/Polynomials.jl

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -251,23 +251,19 @@ dot(p1::Poly, p2::Poly) = p1 * p2
251251
-(p::Poly) = Poly(-p.a, p.var)
252252
-{T<:Number}(p::Poly, c::T) = +(p, -c)
253253
+{T<:Number}(c::T, p::Poly) = +(p, c)
254-
function +{T<:Number}(p::Poly, c::T)
255-
if length(p) < 1
256-
return Poly([c,], p.var)
257-
else
258-
p2 = copy(p)
259-
p2.a[1] += c;
260-
return p2;
261-
end
254+
function +{S,T<:Number}(p::Poly{S}, c::T)
255+
U = promote_type(S,T)
256+
degree(p) == 0 && return Poly(U[c], p.var)
257+
p2 = U == S ? copy(p) : convert(Poly{U}, p)
258+
p2[0] += c
259+
return p2
262260
end
263-
function -{T<:Number}(c::T, p::Poly)
264-
if length(p) < 1
265-
return Poly(T[c,], p.var)
266-
else
267-
p2 = -p;
268-
p2.a[1] += c;
269-
return p2;
270-
end
261+
function -{T<:Number,S}(c::T, p::Poly{S})
262+
U = promote_type(S,T)
263+
degree(p) == 0 && return Poly(U[c], p.var)
264+
p2 = convert(Poly{U}, -p)
265+
p2[0] += c
266+
return p2
271267
end
272268

273269
function +{T,S}(p1::Poly{T}, p2::Poly{S})

test/runtests.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,3 +283,9 @@ pint = polyint(p)
283283
@test isnan(p(1)) # p(1) evaluates to NaN
284284
@test isequal(pder, Poly([NaN])) # derivative will give Poly([NaN])
285285
@test isequal(pint, Poly([NaN])) # integral will give Poly([NaN])
286+
287+
## proper conversions in arithmetic with different element-types #94
288+
p = Poly([0,one(Float64)])
289+
@test Poly{Complex{Float64}} == typeof(p+1im)
290+
@test Poly{Complex{Float64}} == typeof(1im-p)
291+
@test Poly{Complex{Float64}} == typeof(p*1im)

0 commit comments

Comments
 (0)