Create a gist now

Instantly share code, notes, and snippets.

Symbolic Differentiation in Julia
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment