How to simplify symbolic expression using Calculusjl

Here is a very simple example of what im doing:

using Calculus

Calculus.differentiate("286-20*x^2", :x) |> simplify |> eval

:(-(20 * (2x)))

UndefVarError: x not defined

Is there any way to further simplify this to -40x? It can be done in SymPy but I would rather use pure Julia.

1 Like

mmm, i read the code of Calculus.jl and it shouldn’t be possible to do that, as the simplifications are done with respect to the x variable, not the numbers. i was playing with the package and i wrote this code to correctly evaluate the result:

function _symreplace(expr2::Expr,symbol::Symbol,newvalue)
    for i in 1:length(expr2.args)
        if typeof(expr2.args[i]) == Expr
            _symreplace(expr2.args[i],symbol,newvalue)  
        else
            if expr2.args[i] == symbol
            expr2.args[i] = newvalue
            end
        end
    end
    return Calculus.simplify(expr2)
end

function symreplace(expr::Expr,kv::Pair{Symbol,T1}) where T1 <: Union{Symbol,Expr,T} where T <: Number
    symbol = first(kv)
    newvalue = last(kv)
    expr2 = copy(expr)
    return _symreplace(expr2,symbol,newvalue)
end

function symreplace(kv::Pair{Symbol,T1}) where T1 <: Union{Symbol,Expr,T} where T <: Number
    return expr -> symreplace(expr,kv)
end
 

you can use on your expression in the following way:

julia> Calculus.differentiate("286-20*x^2", :x) |> simplify |> symreplace(:x=>2)
-80
2 Likes