# How to turn the function into expression?

I have some function f(x,y,z) and I want to use some commands like f.coefficient({y:1}) on it, but it's no more possible if it's a function. I would be greatfull for help

edit retag close merge delete

1

You should write down all the steps needed to reconstruct your function f.

Could you tell me how to do that? Let's say I have function f(x,y) = x^2 and I'd like to have just an expression f = x^2

Instead of "I have some function f(x, y, z)", please paste the actual code you wrote, for example f(x, y, z) = x*y*z + x*x*y + 5*y*z^2 + 3*x*y^2.

Also, instead of "I want to use some commands like [...] on it, but it is no more possible if it's a function", you could give an example of input and output that works, and an example of input that does not work, and say what you were expecting to get, and what error message you got.

Sort by » oldest newest most voted Suppose we have an ordinary function

sage: def f(x,y,z):
....:     return x^2 - y + z^3


or (which is the same, but shorter)

sage: f = lambda x,y,z: x^2 - y + z^3


Evaluating the function at arguments of the desired type, we can work with the result, e.g. symbolically:

sage: var('x,y,z')
sage: f(x,y,z).coefficient(y)
-1


or with polynomials:

sage: R.<x,y,z> = QQ[]
sage: f(x,y,z).coefficient({y : 1})
-1


However, the latter variant does not work when f is instead a SageMath callable symbolic expression:

sage: f(x,y,z) = x^2 - y + z^3


because it will always output a symbolic expression. So in order to work with polynomials, you have to do:

sage: R(f(x,y,z)).coefficient({y : 1})
-1


instead (or better: define an ordinary function, as above).

In my opinion, this is one of the reasons why having this notation for callable symbolic expressions is bad.

Side note: in SageMath it is often very reasonable to use expressions instead of functions. Many facilities are designed around this, accepting an expression and a list of variables, so the expression will be interpreted as a function of the specified variables. For example, to take a derivative with diff you can specify the variable with respect to which you want to differentiate.

more