# Can you please help with the construction of the piecewise function specified in the details and its plotting?

Anonymous

I want to define and then plot a piecewise function on [-2,2] which is 0.0 on [-2,-1] and on [1,2], and which is (in LaTeX notation) $\exp(-x^2/(1-x^2))$ on (-1,1). I am newcomer to SAGE and tried several variants according to the Reference manual, but failed every time. Some of the error messages are posted below. Can you please offer a SAGE solution for defining of functions in SAGE which are calculated with more than two expression on more than two respective intervals, and such that some of the expression may not be polynomials? Please note that for my purposes I will need to create parametric plots in 3D with parametrizations where the fx, fy and fz will be piecewise functions of the above-said type. I already know how to create the respective 3D plots in SAGE if fx, fy, and fz are well-defined in SAGE.

edit retag close merge delete

1

Can you post what you have tried so we can try and see why it fails?

( 2015-09-24 02:37:12 +0200 )edit

Sort by » oldest newest most voted

You can get the documentation about piecewise functions by typing Piecewise? In your particular case, you can do:

sage: f1(x) = 0
sage: f2(x) = exp(-x^2/(1-x^2))
sage: f = Piecewise([[(-2,-1),f1],[(-1,1),f2],[(1,2),f1]])
sage: f.plot()


EDIT : i did not answer the second part of your question. Indeed, if you do:

sage: g(x) = x
sage: h(x) = x^2
sage: parametric_plot3d([f, g, h], (x, -2, 2))


Then you get the following error:

AttributeError: PiecewisePolynomial instance has no attribute '__float__'


This is because parametric_plot3d needs to evaluate the function f with the __float__ method that does not exists for piecewise functions. However, piecewise finctions are able to evaluate on floating points (with the __call__ method):

sage: f(0.1)
0.989949833766045


So, a possible wotrkaround is to redirect the __float__ method for piecewise functions to the __call__ method that currently works:

sage: f.__float__ = f.__call__


Now, the following works:

sage: parametric_plot3d([f, g, h], (x, -2, 2))

more

Thank you -- your initial recommendation worked just fine!

( 2015-10-08 16:03:39 +0200 )edit

I am afraid you can't do a 3D parametric plot with Piecewise.

I suggest to use a python dict to define the functions, for example:

F = {(-2,-1):[t,e^-1,0], (-1,1):[t,e^-t^2,0], (1,2):[t,e^-1,0]}
G = Graphics()
for k in F.keys():
G += parametric_plot3d(F[k],k)
G.show()

more

Thank you for this helpful instruction. Fortunately, I need piecewise definitions only in the univariate case. In the multivariate case it is then possible to handle the challenges by skillful using only radial-base and tensor-product constructions which are both based on the univariate case.

( 2015-10-08 16:03:44 +0200 )edit