Hi,

On 2017-02-07, [email protected] <[email protected]> wrote:
> I have not been able to use f as a parameter. To use a simpler example, 
> what is the SAGE code corresponding to this Mathematica code:
> f[x_]:=1+x+x^2
> g[x_]:=1+x+x^2+x^3
> Ex[f_]:=Expand[f[x]^2]
> Ex[f]
>
> 1 + 2 x + 3 x^2 + 2 x^3 + x^4
>
> Ex[g]
>
> 1 + 2 x + 3 x^2 + 4 x^3 + 3 x^4 + 2 x^5 + x^6

This is half a SageMath question and half a Python question (Python is
the main language in SageMath):

  sage: f(x) = 1+x+x^2
  sage: g(x) = 1+x+x^2+x^3
  sage: Ex = lambda f: (f^2).expand()
  sage: Ex(f)
  x |--> x^4 + 2*x^3 + 3*x^2 + 2*x + 1
  sage: Ex(g)
  x |--> x^6 + 2*x^5 + 3*x^4 + 4*x^3 + 3*x^2 + 2*x + 1

Note that in the above example both f and g are symbolic functions. If
you just want them to be expressions in x, use
  sage: f = 1+x+x^2
  sage: g = 1+x+x^2+x^3
instead.

Also note that "lambda" is a Python construct that isn't special to
SageMath. It allows you to create a function (here I really mean a
function in the sense of programming, not a symbolic function) on the
fly. Alternatively (which makes sense in more complicated examples),
you could define Ex like this:
  sage: def Ex(f):
  ....:     return (f^2).expand()
  ....: 

Note of course that the above definitions of Ex do *not* change the
meaning of f, even though it appears as a variable in the definition of
Ex (of course, the scope of the local variable f end with the definition
of Ex).

I thought that the following is possible as well:
  sage: Ex(f_) = (f_^2).expand()
  sage: Ex(f)
  (x^2 + x + 1)^2
but as you see it doesn't give the expected answer. Reason: In the
definition of Ex, (f_^2).expand() is expanded *before* you insert f for
f_.

The last approach is bad for a second reason:
   sage: Ex(f_) = (f_^2).expand()
has the side-effect of defining f_ as a symbolic variable. In
particular, if you did use f instead of f_, it would override the
original meaning of f:
   sage: f
   x |--> x^2 + x + 1
   sage: Ex(f) = (f^2).expand()
   sage: f
   f

Generally, my recommendation is to avoid using the implicit definition
of symbolic functions. It wouldn't work in programs anyway, as it only
works since SageMath uses a preparser on interactive input:
  sage: preparse("f(y) = sin(y)+y^3")
  '__tmp__=var("y"); f = symbolic_expression(sin(y)+y**Integer(3)).function(y)'

That's what SageMath turns your input into, so that Python can
understand it.

Best regards,
Simon

-- 
You received this message because you are subscribed to the Google Groups 
"sage-support" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sage-support.
For more options, visit https://groups.google.com/d/optout.

Reply via email to