Skip to content

Commit b5d46f9

Browse files
committed
Some fixes for Polynomials with non-Real types
I was sad to find that my Polynomials-with-modular-arithmetic example had broken at some point. These were the couple of changes I needed to get that working again.
1 parent 2557660 commit b5d46f9

File tree

3 files changed

+36
-3
lines changed

3 files changed

+36
-3
lines changed

src/Polynomials.jl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ immutable Poly{T<:Number}
6969
return new(zeros(T,1), @compat Symbol(var))
7070
else
7171
# determine the last nonzero element and truncate a accordingly
72-
a_last = max(1,findlast(a))
72+
a_last = max(1,findlast(x->x!=zero(T), a))
7373
new(a[1:a_last], @compat Symbol(var))
7474
end
7575
end
@@ -356,7 +356,7 @@ function polyval{T,S}(p::Poly{T}, x::S)
356356
if lenp == 0
357357
return zero(R) * x
358358
else
359-
y = convert(R, p[end]) + 0*x
359+
y = convert(R, p[end]) + zero(T)*x
360360
for i = (endof(p)-1):-1:0
361361
y = p[i] + x*y
362362
end

src/show.jl

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,21 @@ function printexponent(io,var,i)
1515
end
1616

1717
function printterm{T}(io::IO,p::Poly{T},j,first)
18+
pj = p[j]
19+
if pj == zero(T)
20+
return false
21+
end
22+
first || print(io, " + ")
23+
if pj != one(T) || j == 0
24+
print(io, '(')
25+
show(io,pj)
26+
print(io, ") ")
27+
end
28+
printexponent(io,p.var,j)
29+
true
30+
end
31+
32+
function printterm{T<:Real}(io::IO,p::Poly{T},j,first)
1833
pj = p[j]
1934
if pj == zero(T)
2035
return false

test/runtests.jl

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,6 @@ p1 = Poly([4,5,6])
184184
p1[0:1] = [7,8]
185185
@test all(p1[0:end] .== [7,8,6])
186186

187-
188187
## conjugate of poly (issue #59)
189188
as = [im, 1, 2]
190189
bs = [1, 1, 2]
@@ -202,3 +201,22 @@ types = [Int, UInt8, Float64]
202201
for t in types
203202
@test t == eltype(Poly{t})
204203
end
204+
205+
## Polynomials with non-Real type
206+
import Base: +, *, -
207+
immutable Mod2 <: Number
208+
v::Bool
209+
end
210+
+(x::Mod2,y::Mod2) = Mod2(x.v$y.v)
211+
*(x::Mod2,y::Mod2) = Mod2(x.v&y.v)
212+
-(x::Mod2,y::Mod2) = x+y
213+
-(x::Mod2) = x
214+
Base.one(::Type{Mod2}) = Mod2(true)
215+
Base.zero(::Type{Mod2}) = Mod2(false)
216+
Base.convert(::Type{Mod2},x) = Mod2(convert(Bool,x))
217+
Base.convert(::Type{Bool},x::Mod2) = x.v
218+
219+
# Test that none of this throws
220+
p = Poly([Mod2(true),Mod2(false)])
221+
repr(p)
222+
p(Mod2(false))

0 commit comments

Comments
 (0)