On 9/13/07, Justin C. Walker <[EMAIL PROTECTED]> wrote:
> A question about callable functions: I would like to create one, say
> "f(x,y)=x^2+y^2".  There are several ways to do this:

Why.  What problem are you trying to solve?

>   - f = x^2+y^2
>     This works but "f(a,b)" fails (it's not really "callable")

This is a symbolic expression.  You can do:

  f(x=a, y=b)

or


  f.subs(x=a, y=b)

>
>   - R.<x,y> = PolynomialRing(ZZ)
>     g = x^2+y^2
>     This works and "g(a,b)" does what I want.  It seems kind
>     of heavy-weight, though (I've now got a polynomial ring
>     floating around when I don't really need it).

Actually polynomial rings aren't very big.  They're just a few bites. :-)

> sage: h(x,y)=x^2+y^2
> sage: h
> (x, y) |--> y^2 + x^2
> sage: h(0,1)
> 1
> sage: print h(0,1)
>                                         1
> sage: type(h(0,1))
> <class 'sage.calculus.calculus.SymbolicArithmetic'>
>
> So, questions:
>
>   - why is h(0,1) not an 'Integer'?  Does that matter?  I have some
> code (hacks, admittedly) that wants to be sure it's dealing with
> integers.

h(0,1) is a symbolic expression.  If you want an integer, you would
have to write Integer(h(0,1)).

>   - The fact that 'print h(0,1)' produces a bizarre result is really
> a bother, because I can't bank on formatting (unless I am missing
> something; it wouldn't be the first time, of course).

It's ascii art.  If you just need a normal string without any
ascii art, do
   print repr(h(0,1))

>   - Is there some 4th alternative that I missed?

Yes, there are two more, which might be fine, depending on
your application:

def h(x,y):
       return x^2 + y^2

and

h = lambda x,y: x^2 + y^2

Probably the very last one is exactly what you really want,
unless you want to do arithmetic with it (h^2 doesn't make
any sense).

> To complicate matters, I want to create these things in code, and
> return the result, to be used later, either directly or in other code.

The code analogue of "h(x,y) = x^2 + y^2" is:

sage: preparse('h(x,y) = x^2 + y^2')
'_=var("x,y");h=symbolic_expression(x**Integer(2) +
y**Integer(2)).function(x,y)'

I.e., make x and y symbolic, make the expression x^2 + y^2, and
finally make it into a function of x and y.


> Comments?
>
> Thanks for the help, in advance.

Please ask more questions.

 -- William

--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sage-support
URLs: http://sage.math.washington.edu/sage/ and http://sage.scipy.org/sage/
-~----------~----~----~----~------~----~------~--~---

Reply via email to