From 4d75604fde9f1f378fc30cd307da73fab9aa3311 Mon Sep 17 00:00:00 2001 From: Alejandro Morales Sierra Date: Sun, 9 Nov 2014 11:16:58 +0100 Subject: [PATCH] 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 --- src/differentiate.jl | 5 +++++ test/symbolic.jl | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/src/differentiate.jl b/src/differentiate.jl index cfa0039..2dbc7c6 100644 --- a/src/differentiate.jl +++ b/src/differentiate.jl @@ -242,6 +242,11 @@ end ## hypot ## beta, lbeta, eta, zeta, digamma +## Differentiate for piecewise functions defined using ifelse +function differentiate(::SymbolParameter{:ifelse}, args, wrt) + :(ifelse($(args[1]), $(differentiate(args[2],wrt)),$(differentiate(args[3],wrt)))) +end + function differentiate(ex::Expr, targets::Vector{Symbol}) n = length(targets) exprs = Array(Any, n) diff --git a/test/symbolic.jl b/test/symbolic.jl index f2aaa43..0159959 100644 --- a/test/symbolic.jl +++ b/test/symbolic.jl @@ -91,3 +91,10 @@ end @test isequal(simplify(:(x*3)), :(*(3,x))) @test isequal(simplify(:(x*3*4)), :(*(12,x))) @test isequal(simplify(:(2*y*x*3)), :(*(6,y,x))) + +# +# Tests with ifelse +# +@test isequal(differentiate(:(ifelse(x < 1, exp(x^2), 1/x)), :x), :(ifelse(x < 1,2x * exp(x^2), -1/x^2))) +@test isequal(differentiate(:(ifelse(x <= 0, 0, ifelse(x > 1, 1, x))), : x), + :(ifelse(x <= 0, 0, ifelse(x > 1, 0, 1))))