Skip to content

Commit 4d75604

Browse files
Alejandro Morales SierraAleMorales
authored andcommitted
Add support to calculate analytical derivative of ifelse function (assuming it was used to define piecewise functions).
Use inline expression instead of parse for differentiation of ifelse funtion
1 parent e66de9c commit 4d75604

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
@@ -242,6 +242,11 @@ end
242242
## hypot
243243
## beta, lbeta, eta, zeta, digamma
244244

245+
## Differentiate for piecewise functions defined using ifelse
246+
function differentiate(::SymbolParameter{:ifelse}, args, wrt)
247+
:(ifelse($(args[1]), $(differentiate(args[2],wrt)),$(differentiate(args[3],wrt))))
248+
end
249+
245250
function differentiate(ex::Expr, targets::Vector{Symbol})
246251
n = length(targets)
247252
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)