Skip to content

Commit 1463562

Browse files
committed
add chop method, modify tolerance for truncate, add "variable" method
1 parent 6625231 commit 1463562

File tree

1 file changed

+36
-4
lines changed

1 file changed

+36
-4
lines changed

src/Polynomials.jl

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@ module Polynomials
66
using Compat
77

88
export Poly, poly
9-
export degree, coeffs
9+
export degree, coeffs, variable
1010
export polyval, polyint, polyder, roots, polyfit
1111
export Pade, padeval
1212
export truncate!
1313

1414
import Base: length, endof, getindex, setindex!, copy, zero, one, convert, norm, gcd
1515
import Base: show, print, *, /, //, -, +, ==, divrem, div, rem, eltype
16-
import Base: promote_rule, truncate
16+
import Base: promote_rule, truncate, chop
1717
if VERSION >= v"0.4"
1818
import Base.call
1919
end
@@ -119,14 +119,14 @@ eltype{T}(::Poly{T}) = T
119119
120120
"""
121121
length(p::Poly) = length(p.a)
122+
endof(p::Poly) = length(p) - 1
122123

123124
"""
124125
125126
`degree(p::Poly)`: return degree of polynomial `p`
126127
127128
"""
128129
degree(p::Poly) = length(p) - 1
129-
endof(p::Poly) = length(p) - 1
130130

131131
"""
132132
@@ -137,14 +137,46 @@ coeffs(p::Poly) = p.a
137137

138138
"""
139139
140+
Return the indeterminate of a polynomial, `x`.
141+
142+
* `variable(p::Poly)`: return variable of `p` as a `Poly` object.
143+
* `variable(T<:Number, [:x])`: return poly one(T)*x
144+
* `variable([var::Symbol])`: return polynomial 1x over `Float64`.
145+
146+
"""
147+
variable{T}(p::Poly{T}) = poly(zeros(T,1), p.var)
148+
variable{T<:Number}(::Type{T}, var=:x) = poly(zeros(T,1), var)
149+
variable(var::Symbol=:x) = poly([0.0], var)
150+
151+
"""
152+
140153
`truncate{T}(p::Poly{T}; reltol = eps(T), abstol = eps(T))`: returns a polynomial with coefficients a_i truncated to zero if |a_i| <= reltol*maxabs(a)+abstol
141154
142155
"""
143156
function truncate{T}(p::Poly{T}; reltol = eps(T), abstol = eps(T))
144157
a = coeffs(p)
145158
amax = maxabs(a)
146159
anew = map(ai -> abs(ai) <= amax*reltol+abstol ? zero(T) : ai, a)
147-
return Poly(anew)
160+
return Poly(anew, p.var)
161+
end
162+
163+
"""
164+
165+
`chop(p::Poly{T}; kwargs...)` chop off leading values which are
166+
approximately zero. The tolerances are passed to `isapprox`.
167+
168+
"""
169+
function chop{T}(p::Poly{T}; reltol=zero(T), abstol=2 * eps(T))
170+
c = copy(p.a)
171+
for k=length(c):-1:1
172+
if !isapprox(c[k], zero(T); rtol=reltol, atol=abstol)
173+
resize!(c, k)
174+
return Poly(c, p.var)
175+
end
176+
end
177+
178+
resize!(c,0)
179+
Poly(c, p.var)
148180
end
149181

150182
"""

0 commit comments

Comments
 (0)