public
Last active

Symbolic Differentiation in Julia

  • Download Gist
differentiate.jl
Julia
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
differentiate(x::Number, target::Symbol) = 0
 
function differentiate(s::Symbol, target::Symbol)
if s == target
return 1
else
return 0
end
end
 
function differentiate_sum(ex::Expr, target::Symbol)
n = length(ex.args)
new_args = Array(Any, n)
new_args[1] = :+
for i in 2:n
new_args[i] = differentiate(ex.args[i], target)
end
return Expr(:call, new_args, Any)
end
 
function differentiate_subtraction(ex::Expr, target::Symbol)
n = length(ex.args)
new_args = Array(Any, n)
new_args[1] = :-
for i in 2:n
new_args[i] = differentiate(ex.args[i], target)
end
return Expr(:call, new_args, Any)
end
 
function differentiate_product(ex::Expr, target::Symbol)
n = length(ex.args)
res_args = Array(Any, n)
res_args[1] = :+
for i in 2:n
new_args = Array(Any, n)
new_args[1] = :*
for j in 2:n
if j == i
new_args[j] = differentiate(ex.args[j], target)
else
new_args[j] = ex.args[j]
end
end
res_args[i] = Expr(:call, new_args, Any)
end
return Expr(:call, res_args, Any)
end
 
function differentiate_quotient(ex::Expr, target::Symbol)
return Expr(:call,
{
:/,
Expr(:call,
{
:-,
Expr(:call,
{
:*,
differentiate(ex.args[2], target),
ex.args[3]
},
Any),
Expr(:call,
{
:*,
ex.args[2],
differentiate(ex.args[3], target)
},
Any)
},
Any),
Expr(:call,
{
:^,
ex.args[3],
2
},
Any)
},
Any)
end
 
differentiate_lookup = {
:+ => differentiate_sum,
:- => differentiate_subtraction,
:* => differentiate_product,
:/ => differentiate_quotient
}
 
function differentiate(ex::Expr, target::Symbol)
if ex.head == :call
if has(differentiate_lookup, ex.args[1])
return differentiate_lookup[ex.args[1]](ex, target)
else
error("Don't know how to differentiate $(ex.args[1])")
end
else
return differentiate(ex.head)
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.