Skip to content

Instantly share code, notes, and snippets.

@pocc
Created March 2, 2019 19:45
Show Gist options
  • Save pocc/ff7f99c477b33b3b1a274d27f7c257f6 to your computer and use it in GitHub Desktop.
Save pocc/ff7f99c477b33b3b1a274d27f7c257f6 to your computer and use it in GitHub Desktop.
Derive the provided function for x or for a specific value
# Evaluate a derivative of a single-variable function
# Assume last argument is value/var and all others are function
# Example:
# $ julia derive.jl x^2 + x + 1 1
# > derivative at 1:
# > 2.999999999960656
# $ julia derive.jl x^2 + x + 1 x
# > derivative:
# > 2 * 1 * x ^ (2 - 1) + 1
using Calculus
is_symbolic_derivative = (match(r"\d+", ARGS[end]) === nothing)
if is_symbolic_derivative
polynomial = join(ARGS[1:end-1])
result = differentiate(polynomial, ARGS[end])
println("derivative:\n", result)
else
poly_str = replace(join(ARGS[1:end-1]), r"[A-Za-z]" => "x")
polynomial = eval(Meta.parse(string("x->", poly_str)))
at_value = parse(Int64, ARGS[end])
result = derivative(polynomial, at_value)
println("derivative at ", ARGS[end], ":\n", result)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment