Skip to content

Commit 0e0f775

Browse files
Merge pull request #57 from AleMorales/master
Add support to calculate analytical derivative of ifelse function
2 parents c9570bd + 4d75604 commit 0e0f775

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

src/differentiate.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,11 @@ end
254254
## hypot
255255
## beta, lbeta, eta, zeta, digamma
256256

257+
## Differentiate for piecewise functions defined using ifelse
258+
function differentiate(::SymbolParameter{:ifelse}, args, wrt)
259+
:(ifelse($(args[1]), $(differentiate(args[2],wrt)),$(differentiate(args[3],wrt))))
260+
end
261+
257262
function differentiate(ex::Expr, targets::Vector{Symbol})
258263
n = length(targets)
259264
exprs = Array(Any, n)

test/symbolic.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,3 +91,10 @@ end
9191
@test isequal(simplify(:(x*3)), :(*(3,x)))
9292
@test isequal(simplify(:(x*3*4)), :(*(12,x)))
9393
@test isequal(simplify(:(2*y*x*3)), :(*(6,y,x)))
94+
95+
#
96+
# Tests with ifelse
97+
#
98+
@test isequal(differentiate(:(ifelse(x < 1, exp(x^2), 1/x)), :x), :(ifelse(x < 1,2x * exp(x^2), -1/x^2)))
99+
@test isequal(differentiate(:(ifelse(x <= 0, 0, ifelse(x > 1, 1, x))), : x),
100+
:(ifelse(x <= 0, 0, ifelse(x > 1, 0, 1))))

0 commit comments

Comments
 (0)