SymEngine Not Calculating Function Correctly

See the code from the REPL below. What gives?

julia> using SymEngine

julia> @vars x1, x2, x3
(x1, x2, x3)

julia> f = sin(x1*x2) + exp(x2 + x3) - x3
-x3 + exp(x2 + x3) + sin(x2*x1)

julia> gf_x1 = diff(f,x1)

julia> gf_x2 = diff(f,x2)
x1*cos(x2*x1) + exp(x2 + x3)

julia> gf_x3 = diff(f,x3)
-1 + exp(x2 + x3)

julia> gf_x1(1.,2.,3.)

julia> 2.0*cos(2.0)

julia> gf_x2(1.,2.,3.)

julia> cos(2.0)+exp(5.0)

julia> gf_x3(1.,2.,3)

julia> -1+exp(5.)

Now I’m not sure how SymEngine determines the argument order, but

It seems that you are evaluating x1 = 2; x2 = 1, which would agree with the order these variables appears in the expression.

1 Like

Thank you for your reply. From that perspective, means that x2 and x1 have “swapped” their respective positions. Interesting. Explicitly:

From what I see:
gf_x1 => cos(2.0)
gf_x2 => 2.0*cos(2.0) + exp(4.0)
gf_x3 => -1 + exp(3.)

julia> cos(2.0)

julia> 2.0*cos(2.0) + exp(4.0)

julia> -1 + exp(3.)

I wonder if there is a way to have SymEngine hold respect to the variables as they are originally defined in the parent function f? Must be some trick. Maybe someone out there knows.

As @yuyichao said, the heuristic SymEngine is using here to decide on the order of positional arguments is a bit mysterious. I’d say you shouldn’t use the positional arguments like that anyways and instead use the Pair methods:

julia> using SymEngine

julia> @vars x1, x2, x3
(x1, x2, x3)

julia> f = sin(x1*x2) + exp(x2 + x3) - x3; gf1 = diff(f, x1)

julia> gf_x1(x1 => 1., x2 => 2., x3 => 3.)

julia> 2 * cos(2)

as this is much clearer what is going on.

Also, I should mention that your title is a little misleading. It’s the SymEngine.jl external package that’s causing the mysterious behaviour. This isn’t about julia itself doing something wrong.


Thank you very much for your response also. Sorry about the misleading title. At the time I posted, I wasn’t aware that this was a SymEngine related error until @yuyichao replied . Let me see if there is a way to change it. Sorry but I’m obviously brand new to Julia.

And thank you a second time for the Pair example of using this properly.


No need to apologize, and I’m happy I was able to help.

Welcome to the community!


@yuyichao is right. Just try @vars a,b,c followed by f(a,b,c)

1 Like

I’ve taken the liberty to change the thread title to be more descriptive of the actual problem :slight_smile:


Thank you,@Sukera!