# how to evaluate a constructed expression

Hi. The example below is self explanatory

hexp= "g(x)=" + "x**3"
print(hexp)
eval(hexp)
print(g(2))


The hexp is something that is built according to a given algorithm. What I get is the following (on another example)

f(x)= (-1*x**0+4*x**1-1*x**2) * (-5*x**0+5*x**1+4*x**2) * (2*x**0-5*x**1-5*x**2)
^
SyntaxError: invalid syntax


Tried also with evalf without success. Any help will be appreciated.

edit retag close merge delete

Sort by ยป oldest newest most voted

Alternate answer : use the .function() method of a expression :

sage: str="x**3"
sage: g=eval(str).function(x)
sage: g
x |--> x^3
sage: g(3)
27


Alternate to this alternate : exec (you will also need preparse to be able to define a symbolic function) :

sage: str2="h(x)=x**2"
sage: exec(preparse(str2))
sage: h
x |--> x^2
sage: h(3)
9


BTW :

sage: preparse(str2)
'__tmp__=var("x"); h = symbolic_expression(x**Integer(2)).function(x)'


HTH,

more

That works perfectly!! Thanks a lot.

( 2022-12-22 22:24:05 +0100 )edit

You can use function to define the functions you wish. For example,

sage: hexp = "g(x)=" + "x**3"
sage: func, value = hexp.split("(x)=")
sage: function(func, nargs=1, eval_func=lambda self,x: eval(value))
g
sage: print(g(x))
x^3
sage: print(g(3))
27


Another example:

sage: hexp = "f(x)="+"(-1*x**0+4*x**1-1*x**2) * (-5*x**0+5*x**1+4*x**2) * (2*x**0-5*x**1-5*x**2)"
sage: func, value = hexp.split("(x)=")
sage: function(func, nargs=1, eval_func=lambda self,x: eval(value))
f
sage: print(f(x))
(5*x^2 + 5*x - 2)*(4*x^2 + 5*x - 5)*(x^2 - 4*x + 1)
sage: print(f(3))
-5336


Type function? on the Sage prompt or read the docs for more details.

more

works too. thx

( 2022-12-31 20:27:43 +0100 )edit