Ask Your Question

# How do I exec a function of N variables.

asked 2012-08-21 14:49:37 +0200 This post is a wiki. Anyone with karma >750 is welcome to improve it.

The python code: f(x,y)=sin(x) + cos(y) Can be both differentiated and evaluated.

like this: dfx=diff(f,x); dfy=diff(f,y) then evaluated like this: f(pi/6,pi/9) -> cos(1/9pi) + 1/2 dfx(pi/6,pi/9) -> 1/2sqrt(3)

I'm wanting to do something like: exec("f(t1,t2)=cos(t1)+sin(t2)") so that I can write an @interact function to define the equations of N variables interactively. When I try the above exec I receive the error: "SyntaxError: can't assign to function call"

I can almost do it, but I'm getting into a horrible inelegant tangle of of eval statements in the process!

Is there a clean way to do it with sage?

edit retag close merge delete

## 2 Answers

Sort by » oldest newest most voted Usually needing to use exec is a sign something's wrong with a design, but I don't use @interacts much so maybe it's the right way here. It's definitely a little dangerous for remote use, though: if you give me access to this interact over the net I can probably delete all your files.

The problem is that you're using Sage-specific syntax handles by the Sage prepareser and exec doesn't know what to do with it. You can work around that in a few ways, say by calling the preparser specifically:

sage: reset()
sage: s = "f(t1, t2) = cos(t1) + sin(t2)"
sage: exec(s)
------------------------------------------------------------
File "<string>", line 1
SyntaxError: can't assign to function call (<string>, line 1)

sage: preparse(s)
'__tmp__=var("t1,t2"); f = symbolic_expression(cos(t1) + sin(t2)).function(t1,t2)'
sage: exec(preparse(s))
sage: f
(t1, t2) |--> sin(t2) + cos(t1)


or by using the alternate function syntax:

sage: exec("g = (cos(t1)+sin(t2)).function(t1, t2)")
sage: g
(t1, t2) |--> sin(t2) + cos(t1)


where you'd have to make sure the variables were defined somewhere.

more

## Comments

If you like it, you can "accept" it so that DSM "gets credit" for this :)

Can't quite see how to "accept". Is it a thumbs up or a tick or something else?

answered 2012-08-22 15:56:11 +0200 This post is a wiki. Anyone with karma >750 is welcome to improve it.

Is an embedded exec any more insecure than a live session in which anyone could just write one?

more

## Comments

Nope, once you've given someone the ability to write arbitrary code, they can do anything in the box, exec or otherwise. Hence my preference for interacts which only have sliders and such..

## Your Answer

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

Add Answer

## Stats

Asked: 2012-08-21 14:49:37 +0200

Seen: 591 times

Last updated: Aug 22 '12