Ask Your Question
0

how to evaluate a constructed expression

asked 2022-12-21 21:36:52 +0200

moon gravatar image

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 flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
3

answered 2022-12-22 08:22:22 +0200

Emmanuel Charpentier gravatar image

updated 2022-12-22 08:22:51 +0200

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,

edit flag offensive delete link more

Comments

That works perfectly!! Thanks a lot.

moon gravatar imagemoon ( 2022-12-22 22:24:05 +0200 )edit
1

answered 2022-12-22 00:12:25 +0200

Juanjo gravatar image

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.

edit flag offensive delete link more

Comments

works too. thx

moon gravatar imagemoon ( 2022-12-31 20:27:43 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2022-12-21 21:36:52 +0200

Seen: 150 times

Last updated: Dec 22 '22