Skip to content

Commit

Permalink
consolidate
Browse files Browse the repository at this point in the history
  • Loading branch information
jverzani committed Jan 30, 2023
1 parent 4c37580 commit 0995da3
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 16 deletions.
35 changes: 21 additions & 14 deletions src/common.jl
Original file line number Diff line number Diff line change
Expand Up @@ -208,36 +208,43 @@ vander(::Type{<:AbstractPolynomial}, x::AbstractVector, deg::Integer)


"""
critical_points(p)
critical_points(p, lo, hi)
critical_points(p, I=domain(p); endpoints::Bool=true)
Return critical points (sorted zeros of derivative) or critical points in `[l,r]` with `l` and `r` included, either possibly infinite.
Returns critical points (sorted zeros of the derivative) or, if `endpoints=true` critical points in `I` where finite endpoints of `I` are included. `I` defaults to the `p`'s `domain`.
Can be used with `findmax`, `findmin`, `argmax`, `argmin`, `extrema`, etc.
Can be used in conjuction with `findmax`, `findmin`, `argmax`, `argmin`, `extrema`, etc.
## Example
```
x = variable()
p = x^2 - 2
cps = Polynomials.critical_points(p, -Inf, Inf)
findmin(p, cps) # (-2, 2)
cps = Polynomials.critical_points(p)
findmin(p, cps) # (-2.0, 2.0)
argmin(p, cps) # 0.0
extrema(p, cps) # (-2.0, Inf)
cps = Polynomials.critical_points(p, (0, 2))
extrema(p, cps) # (-2.0, 2.0)
```
"""
function critical_points(p::AbstractPolynomial{T}) where {T <: Real}
function critical_points(p::AbstractPolynomial{T}, I = domain(p); endpoints::Bool=true) where {T <: Real}
l, r = extrema(I)

q = Polynomials.ngcd(derivative(p), derivative(p,2)).v
real.(filter(isreal, roots(q)))
end
pts = sort(real.(filter(isreal, roots(q))))
pts = filter(x -> l x r, pts)

function critical_points(p::AbstractPolynomial{T}, l, r = -l) where {T <: Real}
l, r = l < r ? (l,r) : (r,l)
rs = critical_points(p)
pts = Iterators.flatten((l, r, rs))
sort(collect(Iterators.filter(x -> l x r, pts)))
!endpoints && return pts

l !== first(pts) && pushfirst!(pts, l)
r != last(pts) && push!(pts, r)
pts
end






"""
integrate(p::AbstractPolynomial)
Expand Down
7 changes: 5 additions & 2 deletions test/StandardBasis.jl
Original file line number Diff line number Diff line change
Expand Up @@ -903,9 +903,12 @@ end
@testset "critical points" begin
for P in (Polynomial, ImmutablePolynomial)
p = fromroots(P, [-1,-1, 2]) |> integrate
cps = Polynomials.critical_points(p)
cps = Polynomials.critical_points(p, (-5,5); endpoints=false)
@test all(cps .≈ [-1, 2])
cps = Polynomials.critical_points(p, -Inf, Inf)
cps = Polynomials.critical_points(p, (0,5); endpoints=false)
@test all(cps .≈ [2])

cps = Polynomials.critical_points(p)
m, i = findmin(p, cps)
@test m -6.0
x = argmin(p, cps)
Expand Down

0 comments on commit 0995da3

Please sign in to comment.