Skip to content

Commit 23df2b3

Browse files
authored
Merge pull request #108 from JuliaAlgebra/st/fix-jacobian
Fix differentiate of AbstractArrays
2 parents dc626ea + 787e387 commit 23df2b3

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

src/differentiation.jl

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ will help the compiler infer the return type.
1717
differentiate(p::AbstractArray{<:AbstractPolynomialLike, N}, vs, deg::Union{Int, Val}=1) where N
1818
1919
Differentiate the polynomials in `p` by the variables of the vector or tuple of variable `vs` and return an array of dimension `N+deg`.
20+
If `p` is an `AbstractVector` this returns the Jacobian of `p` where the i-th row containts the partial
21+
derivaties of `p[i]`.
2022
2123
### Examples
2224
@@ -25,6 +27,7 @@ p = 3x^2*y + x + 2y + 1
2527
differentiate(p, x) # should return 6xy + 1
2628
differentiate(p, x, Val{1}()) # equivalent to the above
2729
differentiate(p, (x, y)) # should return [6xy+1, 3x^2+1]
30+
differentiate( [x^2+y, z^2+4x], [x, y, z]) # should return [2x 1 0; 4 0 2z]
2831
```
2932
"""
3033
function differentiate end
@@ -40,11 +43,11 @@ differentiate(p::RationalPoly, v::AbstractVariable) = (differentiate(p.num, v) *
4043
const ARPL = Union{APL, RationalPoly}
4144

4245
function differentiate(ps::AbstractArray{PT}, xs::AbstractArray) where {PT <: ARPL}
43-
differentiate.(reshape(ps, (1, size(ps)...)), reshape(xs, :))
46+
differentiate.(reshape(ps, (size(ps)..., 1)), reshape(xs, 1, :))
4447
end
4548

4649
function differentiate(ps::AbstractArray{PT}, xs::Tuple) where {PT <: ARPL}
47-
differentiate.(reshape(ps, (1, size(ps)...)), xs)
50+
differentiate(ps, collect(xs))
4851
end
4952

5053

test/differentiation.jl

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
@testset "Differentiation" begin
2-
Mod.@polyvar x y
2+
Mod.@polyvar x y z
33
@test differentiate(3, y) == 0
44
@test differentiate.([x, y], y) == [0, 1]
55
@test differentiate([x, y], (x, y)) == Matrix(1.0I, 2, 2) # TODO: this can be just `I` on v0.7 and above
@@ -34,6 +34,10 @@
3434
@test isa(p, Matrix{<:AbstractPolynomial{Float64}})
3535
@test p == [4.0 6.0y; 6.0y 6.0x+24.0y]
3636

37+
f = [x^2+y, z^2+4x]
38+
@test differentiate(f, [x, y, z]) == [2x 1 0; 4 0 2z]
39+
@test differentiate(f, (x, y, z)) == [2x 1 0; 4 0 2z]
40+
3741
@testset "differentiation with Val{}" begin
3842
@test @inferred(differentiate(x, x, Val{0}())) == x
3943
@test @inferred(differentiate(x, x, Val{1}())) == 1

0 commit comments

Comments
 (0)