# How to simplify symbolic expression using Calculusjl

**URL:** https://discourse.julialang.org/t/how-to-simplify-symbolic-expression-using-calculusjl/32036
**Category:** New to Julia
**Created:** [December 9, 2019, 5:31am UTC](https://discourse.julialang.org/t/how-to-simplify-symbolic-expression-using-calculusjl/32036 "2019-12-09T05:31:42Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![ASF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/asf/32/10610_2.png) [@ASF](https://discourse.julialang.org/u/ASF)
#### Post date: [December 9, 2019, 5:31am UTC](https://discourse.julialang.org/t/how-to-simplify-symbolic-expression-using-calculusjl/32036/1 "2019-12-09T05:31:42Z")

</div>

Here is a very simple example of what im doing:

```julia
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.

---

<div class="post-metadata">

### Author: ![longemen3000](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/longemen3000/32/7298_2.png) [@longemen3000](https://discourse.julialang.org/u/longemen3000)
#### Post date: [December 9, 2019, 7:07am UTC](https://discourse.julialang.org/t/how-to-simplify-symbolic-expression-using-calculusjl/32036/2 "2019-12-09T07:07:22Z")

</div>

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:

```julia
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
julia> Calculus.differentiate("286-20*x^2", :x) |> simplify |> symreplace(:x=>2)
-80

```
