Quantcast
Channel: Planet Sage
Viewing all articles
Browse latest Browse all 414

Sébastien Labbé: Python function vs Symbolic function in Sage

$
0
0

This message is about differences between a Python function and a symbolic function. This is also explained in the Some Common Issues with Functions page in the Sage Tutorial.

In Sage, one may define a symbolic function like:

sage:f(x)=x^2-1

And draw it using one the following way (both works):

sage:plot(f,(x,-10,10))sage:plot(f(x),(x,-10,10))
/~labbe/Files/2013/plot_f_symb.png

Here both f and f(x) are symbolic expressions:

sage:type(f)<type'sage.symbolic.expression.Expression'>sage:type(f(x))<type'sage.symbolic.expression.Expression'>

although there are different:

sage:fx|-->x^2-1sage:f(x)x^2-1

Now if f is a Python function defined with a def statement:

sage:deff(x):....:ifx>0:....:returnx....:else:....:return0

It is really a Python function:

sage:f<functionfat0xb933470>sage:type(f)<type'function'>

As above, one can draw the function f:

sage:plot(f,(x,-10,10))
/~labbe/Files/2013/plot_f_python.png

But be carefull, drawing f(x) will not work as expected:

sage:plot(f(x),(x,-10,10))
/~labbe/Files/2013/plot_fx_python.png

Why? Because, the python function f gets evaluated on the variable x and this may either raise an exception depending on the definition of f or return some result which might not be a symbolic expression. Here f(x) gets always evaluated to zero because in the definition of f, bool(x > 0) returns False:

sage:xxsage:bool(x>0)Falsesage:f(x)0

Hence the following constant function is drawn:

sage:plot(0,(x,-10,10))

which is not what we want.


Viewing all articles
Browse latest Browse all 414

Trending Articles