How shoudl I evaluate a symbolic expression for a given value of a local variable?

Suppose I have an expression that I want to symbolically differentiate using the Calculus package, and then create a function in Julia evaluating this expression at a given value of the variable x. For instance,

using Calculus
expression_F=“x^3”
expression_f= differentiate(expression_F,:x)
f(x)=eval(expression_f)

However this function is broken, as eval does not understand that I want to evaluate “x” to the local variable (not to a global one, see
https://github.com/JuliaLang/julia/issues/2386)

julia> f(8)
ERROR: UndefVarError: x not defined

Many thanks if you could help me!

Try f = eval(:(x->$expression_f)). That creates a function expression containing the expression to evaluate, so that x is bound within the expression. Then the function expression is evaluated, producing a function object you can call.

1 Like

Many thanks! However, I’m not really understanding how this works. For if, I just define my expression by hand as in the following example, it doesn`t work!

julia> expression_F=“x^3”
“x^3”

julia> F(x)=eval(:(x->$expression_F))
F (generic function with 1 method)

julia> F(2)
#11 (generic function with 1 method)

Note that this is a string and not an expression.

julia> F(x)=eval(:(x->$expression_F))

As with any function, this means that when we execute F(x) we get the result of computing the function body. The function body is

eval(:(x->$expression_F))

which is here evaluating the expression x -> "x^3". This expression gives an anonymous function that takes one argument and returns the string “x^3”.

Ok, so in the end we get

julia> f = F("whatevs") # the argument is not used
#9 (generic function with 1 method)

julia> f("something else") # the argument is not used
"x^3"

Also, please see PSA: how to quote code with backticks.

2 Likes