ASKSAGE: Sage Q&A Forum - Latest question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Sat, 02 Feb 2019 18:17:24 -0600Piecewise in SageTeXhttp://ask.sagemath.org/question/45278/piecewise-in-sagetex/ Hi, am trying to use the "piecewise" command in SageTeX but i get an error no matter what i try. It is like the SageTeX doesnt know what "piecewise" means, like the command "piecewise" is not implemented in SageTeX.
I tried different ways of typing the piecewise command in sage terminal and it works fine.
sage: f=piecewise([[(-15,0),6],[(0,44),sqrt(-x^2+52*x+36)]])
and
sage: f=piecewise([((-15,0), 6), ([0,44], sqrt(-x^2+52*x+36))]); f
But when i do the same in sagetex and compile with
# sage filename.sagetex.sage
Then i get
Processing Sage code for modul-2.tex...
Sage commandline 0 (line 193)
Sage commandline 1 (line 200)
Sage commandline 2 (line 209)
/usr/lib/python2.7/site-packages/sagetex.py:209: DeprecationWarning: Substitution using function-call syntax and unnamed arguments is deprecated and will be removed from a future release of Sage; you can use named arguments instead, like EXPR(x=..., y=...)
DELETED LINK
result = eval(preparse(splitup[i][2]), globals, locals)
Sage commandline 3 (line 239)
Sage commandline 4 (line 246)
Sage commandline 5 (line 252)
/usr/lib/python2.7/site-packages/sagetex.py:218: DeprecationWarning: Substitution using function-call syntax and unnamed arguments is deprecated and will be removed from a future release of Sage; you can use named arguments instead, like EXPR(x=..., y=...)
DELETED LINK
exec(preparse(splitup[i][2]), globals, locals)
Sage commandline 6 (line 309)
Sage commandline 7 (line 315)
Sage commandline 8 (line 322)
Sage commandline 9 (line 496)
Sage commandline 10 (line 505)
Sage commandline 11 (line 520)
Sage commandline 12 (line 530)
Sage commandline 13 (line 538)
Sage commandline 14 (line 559)
**** Error in Sage code on line 561 of modul-2.tex! Traceback follows.
Traceback (most recent call last):
File "modul-2.sagetex.sage.py", line 119, in <module>
""", globals(), locals(), False)
File "/usr/lib/python2.7/site-packages/sagetex.py", line 196, in commandline
splitup = self.split_sage_cmds(s)
File "/usr/lib/python2.7/site-packages/sagetex.py", line 138, in split_sage_cmds
starts[0] = re.search(prompt, s).start()
AttributeError: 'NoneType' object has no attribute 'start'
**** Running Sage on modul-2.sage failed! Fix modul-2.tex and try again.
I tried inside env, sagecommandline and \sage{} and env. sageblock.
I didnt get error in sageblock but then when i tried to plot the function later i got the error anyways.
Can anyone help me from here? How can i define piecewise functions in SageTeX??Martin MÃ¥rtenssonSat, 02 Feb 2019 18:17:24 -0600http://ask.sagemath.org/question/45278/piecewise defined function via defhttp://ask.sagemath.org/question/41061/piecewise-defined-function-via-def/I've made the following experiment with Sage:
def f(x):
if (0<= x<= 1/2):
return 1
else:
return 0
assume(0<= x<= 1/2)
show(f(x))
show(f(1/3))
However I get outputs 0 and 1 respectively. Can someone clarify please? Thanks.newuserSat, 10 Feb 2018 20:43:20 -0600http://ask.sagemath.org/question/41061/Piecewise Symbolic Function with Conditional Statementhttp://ask.sagemath.org/question/38347/piecewise-symbolic-function-with-conditional-statement/I wish to incorporate a conditional Python expression (`if ... else ...`) in a symbolic function.
Suppose I have a piecewise function *k(n)* defined for *n* = 1,2,3... as in the following pseudocode:
k(n) =
2 if n = 1
n otherwise
I compose this with another function *g(x)* and wish to integrate the result. For example,
f(x)=g(x)/k(n)
f(n=...).integrate(x, 0, 1)
How can implement a non-evaluating conditional in a symbolic Sage function?terrygarciaFri, 21 Jul 2017 11:23:17 -0500http://ask.sagemath.org/question/38347/Integrate piecewise function with change of variablehttp://ask.sagemath.org/question/37114/integrate-piecewise-function-with-change-of-variable/I would like to integrate a piecewise defined function while operating a change of variable. I start by defining the function and another variable involved in the change of variable:
phi(x) = piecewise([([-1,1], (1-abs(x))*(1-abs(x))*(1+2*abs(x)))]);
phi(x) = phi.extension(0);
h=pi/n;
h=h.n();
What I would like to do is integrate the function `phi(x/h-1)` between `0` and `pi` so I try it and results in
integral(phi(x/h-1),x,0,pi)
ValueError: substituting the piecewise variable must result in real number
So I then try to use another variable which I try to define to be 'real'
t=var('t')
assume(t,'real');
integral(phi(t/h-1),t,0,pi)
but it results in the same error... Now I try the "lambda" method since it worked when calling the `plot` function with the same change of variable; but fail again
integral(lambda t: phi(t/h-1),t,0,pi)
TypeError: unable to convert <function <lambda> at 0x16d71f140> to a symbolic expression
Now I try to use another integration method with `definite_integral` but get the same errors, only different for the "lambda" method
definite_integral(lambda x: phi(x/h-1),x,0,pi)
TypeError: cannot coerce arguments: no canonical coercion from <type 'function'> to Symbolic Ring
Is there any way around this? I really do not know what else to try...
jrojasquTue, 28 Mar 2017 18:28:56 -0500http://ask.sagemath.org/question/37114/Substitute piecewise function variablehttp://ask.sagemath.org/question/37066/substitute-piecewise-function-variable/I have the following piecewise function:
phi = piecewise([([-1,1], (1-abs(x))*(1-abs(x))*(1+2*abs(x)))]);
phi = phi.extension(0);
It appears to be a valid function since I can obtain/plot its values for any 'x'. But whenever I try to substitute the variable, it does not work. For example,
phi(2)
0
but if I declare another variable 'h' and try to input that variable into the piecewise function, it does not appear to work:
h=pi/2
phi(h)
TypeError: self must be a numeric expression
At first I thought that 'h' was not a 'numeric' or 'real' value, but when I test it, it is a real value:
h.is_real()
True
How can I overcome this? How can I successfully operate a variable substitution in my piecewise function?jrojasquFri, 24 Mar 2017 14:39:26 -0500http://ask.sagemath.org/question/37066/integral of piecewise function: errorhttp://ask.sagemath.org/question/36536/integral-of-piecewise-function-error/I get a weird error when trying to take an integral of a very simple piecewise function:
blah = piecewise([((0, 0.01), 0.0001), ([0.01, 0.02], 0.0002), ((0.02, 0.03), 0.0003)])
blah.integral(x, 0.01, 0.025)
gives:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-132-73d5f18533d2> in <module>()
1 blah = piecewise([((Integer(0), RealNumber('0.01')), RealNumber('0.0001')), ([RealNumber('0.01'), RealNumber('0.02')], RealNumber('0.0002')), ((RealNumber('0.02'), RealNumber('0.03')), RealNumber('0.0003')), ([RealNumber('0.03'), RealNumber('0.04')], RealNumber('0.0004'))])
----> 2 blah.integral(x, RealNumber('0.01'), RealNumber('0.025'))
/home/sschyman/Programs/sage-upgrade/local/lib/python2.7/site-packages/sage/symbolic/function_factory.pyc in new_f(ex, *args, **kwds)
400 new_args = list(ex._unpack_operands())
401 new_args.extend(args)
--> 402 return f(ex, *new_args, **kwds)
403 return new_f
/home/sschyman/Programs/sage-upgrade/local/lib/python2.7/site-packages/sage/functions/piecewise.pyc in integral(cls, self, parameters, variable, x, a, b, definite)
793 """
794 if a != None and b != None:
--> 795 F = self.integral(x)
796 return F(b) - F(a)
797
/home/sschyman/Programs/sage-upgrade/local/lib/python2.7/site-packages/sage/symbolic/function_factory.pyc in new_f(ex, *args, **kwds)
400 new_args = list(ex._unpack_operands())
401 new_args.extend(args)
--> 402 return f(ex, *new_args, **kwds)
403 return new_f
/home/sschyman/Programs/sage-upgrade/local/lib/python2.7/site-packages/sage/functions/piecewise.pyc in integral(cls, self, parameters, variable, x, a, b, definite)
828 else:
829 try:
--> 830 assume(start < x)
831 except ValueError: # Assumption is redundant
832 pass
/home/sschyman/Programs/sage-upgrade/local/lib/python2.7/site-packages/sage/symbolic/assumptions.pyc in assume(*args)
513 else:
514 try:
--> 515 x.assume()
516 except KeyError:
517 raise TypeError("assume not defined for objects of type '%s'"%type(x))
AttributeError: 'numpy.bool_' object has no attribute 'assume'
Is this a bug or did I make a mistake?
UPDATE: I uploaded an example to SMC: https://cloud.sagemath.com/projects/34b4b62a-2621-47c8-9bda-cde3a855f995/files/numpy_bool_traceback/stanFri, 10 Feb 2017 07:06:56 -0600http://ask.sagemath.org/question/36536/defining multivariate piecewise functionhttp://ask.sagemath.org/question/36567/defining-multivariate-piecewise-function/I need to define some function like `f(x,y) = x * sin(y)/y if y != 0, x otherwise`, such that `f` can be differentiated. Is there a way to do so? Thanks!maaaaaaartinSat, 11 Feb 2017 07:24:14 -0600http://ask.sagemath.org/question/36567/Evaluating the derivative of piecewise functionshttp://ask.sagemath.org/question/36451/evaluating-the-derivative-of-piecewise-functions/ Hi,
In Sage 7.5 you can numerically evaluate the derivative of a regular symbolic expression using:
sage: h(x) = sin(x)
sage: diff(h)(2).n()
-0.416146836547142
Old **Piecewise** functions could be treated in the same way:
sage: g = Piecewise([([0,2], sin(x)), ((2,3), cos(x))])
... DeprecationWarning ...
sage: diff(g)(1).n()
0.540302305868140
However, new **piecewise** functions don't:
sage: f = piecewise([([0,2], sin(x)), ((2,3), cos(x))])
sage: diff(f)(1).n()
... Error ...
Thanks in advance.
franpenaSat, 04 Feb 2017 12:43:29 -0600http://ask.sagemath.org/question/36451/numerical_integral in piecewise functionhttp://ask.sagemath.org/question/33433/numerical_integral-in-piecewise-function/ If I define a Python function with a numerical integral
def g(x):
var('u')
return numerical_integral(u,0,x)[0]
then it behaves as expected for example when plotting with `plot(g)`. If it is included as part of a piecewise function like
f = piecewise([[(-1,0),-x],[(0,1),g]])
plot(f)
then the plot shows up just fine for Sage 6.9 (which was running on [sagecell.sagemath.org](http://sagecell.sagemath.org/?z=eJwljEEKwyAQAO-B_GFv2YUNmGuhLxEJkq4iWBs2mvj8pnTmNJd5SYCInR7jADenV5zaRP9SqU0LlPYWTZvPaypVovqMjQ13ssaNw88AT9iTbHKlQ9BanBc2xHN3bNHwQhydu6d7_lQM9AWMCiCN&lang=sage)), but for Sage 7.2 (which is running on the [test](http://cosmos.mat.uam.es:8888/?z=eJwljEEKgCAQRfdBd5hdI7iwbdBJREJsFMEsJq2On9F_m_c2fyUPAR8x9R20XZZxqIP4i6lUzpDrRhydTUvMhQLbhFUq-QitTN99eJjhiOTojieh1qjkKGQwph0daS_om7xY8h3k&lang=sage) server) one gets the error message
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-474c66ac1c47> in <module>()
4
5
----> 6 f = piecewise([[(Integer(0),Integer(1)),g]])
7 plot(f)
/home/sc_serv/sage/src/sage/misc/lazy_import.pyx in sage.misc.lazy_import.LazyImport.__call__ (/home/sc_serv/sage/src/build/cythonized/sage/misc/lazy_import.c:3628)()
384 True
385 """
--> 386 return self._get_object()(*args, **kwds)
387
388 def __repr__(self):
/home/sc_serv/sage/local/lib/python2.7/site-packages/sage/functions/piecewise.py in __call__(self, function_pieces, **kwds)
149 function = function()
150 else:
--> 151 function = function(var)
152 function = SR(function)
153 if var is None and len(function.variables()) > 0:
<ipython-input-1-474c66ac1c47> in g(x)
1 def g(x):
2 var('u')
----> 3 return numerical_integral(u,Integer(0),x)[Integer(0)]
4
5
/home/sc_serv/sage/src/sage/gsl/integration.pyx in sage.gsl.integration.numerical_integral (/home/sc_serv/sage/src/build/cythonized/sage/gsl/integration.c:3387)()
329 else:
330 _a=a
--> 331 _b=b
332 W = <gsl_integration_workspace*> gsl_integration_workspace_alloc(n)
333 sig_on()
/home/sc_serv/sage/src/sage/symbolic/expression.pyx in sage.symbolic.expression.Expression.__float__ (/home/sc_serv/sage/src/build/cythonized/sage/symbolic/expression.cpp:10403)()
1384 return float(self._eval_self(float))
1385 except TypeError:
-> 1386 raise TypeError("unable to simplify to float approximation")
1387
1388 def __complex__(self):
TypeError: unable to simplify to float approximation
Am I missing something simple or is this a bug in Sage 7.2?
There is an existing ticket that appears relevant: http://trac.sagemath.org/ticket/14801
paulmassonTue, 17 May 2016 17:10:47 -0500http://ask.sagemath.org/question/33433/Can you please help with the construction of the piecewise function specified in the details and its plotting?http://ask.sagemath.org/question/29545/can-you-please-help-with-the-construction-of-the-piecewise-function-specified-in-the-details-and-its-plotting/ 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.shao-linuxWed, 23 Sep 2015 13:39:52 -0500http://ask.sagemath.org/question/29545/Alternative to piecewise functions?http://ask.sagemath.org/question/26614/alternative-to-piecewise-functions/If I only need indicator functions (the function is 1 in an interval [a, b], 0 outside of it). Is there an alternative to piecewise functions (with all their issues like plotting), which I can use? Thank you!
EDIT: Ok, I had an idea:
indicator(x,a,b)=(sign(x-a)-sign(x-b))/2
That does pretty much what I want.OderynTue, 21 Apr 2015 08:47:42 -0500http://ask.sagemath.org/question/26614/Two piecewise defined functions in one plothttp://ask.sagemath.org/question/8434/two-piecewise-defined-functions-in-one-plot/Is it possible to plot 2 piecewise defined functions to one plot?
I tried:
f = Piecewise([[(-2,1),1],[(1,4),x]])
g = Piecewise([[(-2,1),1],[(1,4),2*x]])
plot([f,g])
but I get the following error message:
{{{id=6|
x_1 = Piecewise([[(-100,t_R),v_0*t],[(t_R,t_R + v_0/a),-1/2*a*(t-t_R)^2 + v_0*t],[(t_R + v_0/a,100),v_0^2/(2*a) + v_0*t_R]])
x_2 = Piecewise([[(-100,2*t_R),v_0*t + s_S],[(t_R,2*t_R + v_0/a),-1/2*a*(t-2*t_R)^2 + v_0*t + s_S],[(2*t_R + v_0/a,100),v_0^2/(2*a) + v_0*(2*t_R) + s_S ]])
///
}}}
{{{id=7|
xp = plot([x_1(t),x_2(t)]);
xp.show(axes_labels=["Zeit t in s","x_1 in m"],xmin=0,xmax=v_0/t_R + t_R,ymin=0)
///
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "_sage_input_137.py", line 10, in <module>
exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("eHAgPSBwbG90KFt4XzEodCkseF8yKHQpXSk7CnhwLnNob3coYXhlc19sYWJlbHM9WyJaZWl0IHQgaW4gcyIsInhfMSBpbiBtIl0seG1pbj0wLHhtYXg9dl8wL3RfUiArIHRfUix5bWluPTAp"),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))' + '\n', '', 'single')
File "", line 1, in <module>
File "/tmp/tmpjQcRVV/___code___.py", line 3, in <module>
xp = plot([x_1(t),x_2(t)]);
File "/opt/sage-4.7.1-linux-64bit-ubuntu_10.04.1_lts-x86_64-Linux/local/lib/python2.6/site-packages/sage/functions/piecewise.py", line 648, in __call__
raise ValueError,"Value not defined outside of domain."
ValueError: Value not defined outside of domain.
}}}
{{{id=13|
f = Piecewise([[(-2,1),1],[(1,4),x]])
g = Piecewise([[(-2,1),1],[(1,4),2*x]])
plot([f,g])
///
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "_sage_input_145.py", line 10, in <module>
exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("ZiA9IFBpZWNld2lzZShbWygtMiwxKSwxXSxbKDEsNCkseF1dKQpnID0gIFBpZWNld2lzZShbWygtMiwxKSwxXSxbKDEsNCksMip4XV0pCnBsb3QoW2YsZ10p"),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))' + '\n', '', 'single')
File "", line 1, in <module>
File "/tmp/tmpSARQLu/___code___.py", line 5, in <module>
exec compile(u'plot([f,g])' + '\n', '', 'single')
File "", line 1, in <module>
File "/opt/sage-4.7.1-linux-64bit-ubuntu_10.04.1_lts-x86_64-Linux/local/lib/python2.6/site-packages/sage/misc/decorators.py", line 657, in wrapper
return func(*args, **kwds)
File "/opt/sage-4.7.1-linux-64bit-ubuntu_10.04.1_lts-x86_64-Linux/local/lib/python2.6/site-packages/sage/misc/decorators.py", line 504, in wrapper
return func(*args, **options)
File "/opt/sage-4.7.1-linux-64bit-ubuntu_10.04.1_lts-x86_64-Linux/local/lib/python2.6/site-packages/sage/plot/plot.py", line 3067, in plot
G = _plot(funcs, (xmin, xmax), **kwds)
File "/opt/sage-4.7.1-linux-64bit-ubuntu_10.04.1_lts-x86_64-Linux/local/lib/python2.6/site-packages/sage/plot/plot.py", line 3105, in _plot
funcs, ranges = setup_for_eval_on_grid(funcs, [xrange], options['plot_points'])
File "/opt/sage-4.7.1-linux-64bit-ubuntu_10.04.1_lts-x86_64-Linux/local/lib/python2.6/site-packages/sage/plot/misc.py", line 138, in setup_for_eval_on_grid
return fast_float(funcs, *vars,**options), [tuple(range+[range_step]) for range,range_step in zip(ranges, range_steps)]
File "fast_eval.pyx", line 1357, in sage.ext.fast_eval.fast_float (sage/ext/fast_eval.c:8418)
File "fast_eval.pyx", line 1377, in sage.ext.fast_eval.fast_float (sage/ext/fast_eval.c:8704)
AttributeError: PiecewisePolynomial instance has no attribute '__float__'
}}}
sagefanThu, 03 Nov 2011 05:40:56 -0500http://ask.sagemath.org/question/8434/help with simple integration of piecewise function?http://ask.sagemath.org/question/24887/help-with-simple-integration-of-piecewise-function/ r = var('r')
Piecewise([[(1,2), 1/floor(r)]]).integral(r,1,2)
Gives an error:
Error in lines ...
AttributeError: 'sage.rings.integer.Integer' object has no attribute 'variables
What am I doing wrong? I note that
Piecewise([[(1,2), 1/floor(r)]]).integral(r)
gives output ``Piecewise defined function with 1 parts, [[(1, 2), r1 |--> integrate(1/floor(r1), r1, 1, r1)]]''.
And that
integrate(1/floor(r1), r1, 1, r1)(2)
gives the same error as the first attempt. Here's the full stacktrace of the error:
EDIT: Thanks. Here's the full stack trace for the error:
File "/Applications/Sage-6.3.app/Contents/Resources/sage/local/lib/python2.7/site-packages/sage/functions/piecewise.py", line 833, in integral
return F(b) - F(a)
File "/Applications/Sage-6.3.app/Contents/Resources/sage/local/lib/python2.7/site-packages/sage/functions/piecewise.py", line 665, in __call__
return self.functions()[n-1](x0)
File "expression.pyx", line 4391, in sage.symbolic.expression.Expression.__call__ (build/cythonized/sage/symbolic/expression.cpp:21933)
File "/Applications/Sage-6.3.app/Contents/Resources/sage/local/lib/python2.7/site-packages/sage/symbolic/callable.py", line 477, in _call_element_
return SR(_the_element.substitute(**d))
File "expression.pyx", line 4242, in sage.symbolic.expression.Expression.substitute (build/cythonized/sage/symbolic/expression.cpp:21183)
File "/Applications/Sage-6.3.app/Contents/Resources/sage/local/lib/python2.7/site-packages/sage/symbolic/integration/integral.py", line 161, in _eval_
if len(x.variables()) == 1:
File "element.pyx", line 344, in sage.structure.element.Element.__getattr__ (build/cythonized/sage/structure/element.c:4022)
File "misc.pyx", line 257, in sage.structure.misc.getattr_from_other_class (build/cythonized/sage/structure/misc.c:1775)
AttributeError: 'sage.rings.integer.Integer' object has no attribute 'variables'NealSun, 16 Nov 2014 16:35:36 -0600http://ask.sagemath.org/question/24887/Am I not inside the domain ?http://ask.sagemath.org/question/24830/am-i-not-inside-the-domain/ x=var('x')
f = Piecewise([[(0,pi/2),-1],[(pi/2,pi),2]])
plot(f(x),(x,0,pi))
**?
ValueError: Value not defined outside of domain.
?**jpapotTue, 11 Nov 2014 01:33:58 -0600http://ask.sagemath.org/question/24830/desolve_rk4 cannot handle a piecewise functionhttp://ask.sagemath.org/question/11062/desolve_rk4-cannot-handle-a-piecewise-function/I am trying to get a numeric solution to a differential equation involving a function that is piecewise (actually defined using an if/else statement). I successfully generated a slopefield using the lambda function, but desolve_rk4 seemingly cannot cope with this syntax. It seems to me that a numeric solver should be able to handle a function defined this way, but perhaps I am just doing something wrong?
Code:
var('t')
def f(t):
if t<5:
return 3
else:
return 0
V=function('V',t)
desolve_rk4(lambda t,V: ((f)-V)/(2.3*1.2),V, ics=(0,0),ivar=t)Groenendael72Thu, 20 Feb 2014 11:26:00 -0600http://ask.sagemath.org/question/11062/Isolines of piecewise linear functionhttp://ask.sagemath.org/question/10914/isolines-of-piecewise-linear-function/Hi,
I'm trying to find out how to plot isolines (in 3D) of the following function :
z = 0.2 x + 0.8 y if x < y and z = 0.6 x+0.4 y if x >= y
Thanks in advance for any help,
PatrickpaterijkWed, 15 Jan 2014 00:47:34 -0600http://ask.sagemath.org/question/10914/what type of object is a function defined with the piecewise command?http://ask.sagemath.org/question/9042/what-type-of-object-is-a-function-defined-with-the-piecewise-command/I understand that in Sage, there are three function-like things: functions, expressions, and python functions. How do you classify functions defined with the `piecewise` command?
Functions defined with the `piecewise` command seem to be a separate class. When I use the `parent()` command on a piecewise function, Sage says it is an "instance." Can you help me understand what that means? Thanks!calc314Thu, 07 Jun 2012 08:32:23 -0500http://ask.sagemath.org/question/9042/Multivariate piecewise function?http://ask.sagemath.org/question/10084/multivariate-piecewise-function/Hi,
How can I define a function like this?
`f(x,y) = x*y` , when (x > 0),(y>0)
`f(x,y) = -x*y`, when (x <= 0), (y <=0)
johnjohnFri, 23 Aug 2013 04:36:21 -0500http://ask.sagemath.org/question/10084/Convolving two functions doesn't work as expectedhttp://ask.sagemath.org/question/10019/convolving-two-functions-doesnt-work-as-expected/Hi all, I'm trying to convolve two functions as follows:
`forget()` <br>
`x = PolynomialRing(QQ, 'x').gen()` <br>
`f1 = Piecewise([[(-1, 1), 1*x^0]])` <br>
`f2 = Piecewise([[(0, 1), x], [(1, 2), -x + 2]])` <br>
`g = f2.convolution(f1)` <br>
`Q = g.plot(rgbcolor=(1,1,0), figsize = 4);` <br>
`g`
I get that g is given by:
> Piecewise defined function with 4 parts, [[(-1, 0), 1/2\*x^2 + x +1/2], [(0, 1), -1/2\*x^2 + 3\*x], [(1, 2), -1/2\*x^2 - x + 4], [(2, 3), 1/2\*x^2 -
3\*x + 9/2]].
Whereas, if computed manually, g is given by:
> Piecewise defined function with 3 parts, [[(-1, 0),
0.5\*x^2 + x + 0.5], [(0, 2),
-0.5\*x^2 + x + 0.5], [(2, 3),
0.5\*x^2 - 3\*x + 4.5]
Why doesn't the one computed by sage match the correct function?
ThisisnotanidSat, 13 Apr 2013 11:31:30 -0500http://ask.sagemath.org/question/10019/Piecewise curve fitting polynomial datahttp://ask.sagemath.org/question/9989/piecewise-curve-fitting-polynomial-data/Hello all. I am curve fitting time series data using polyfit() and it works well for most of my data sets. I have noticed, however, that some data sets begin hyperbolic and move to exponential so as to best fit to two separate equations. What is simple way to fit my data to two different curve equations using Sage? Is there a good mathematical or programmatic method of determining when a data set is best served by piecewise curve fitting? Currently, I can only determine that empirically once the curve is plotted along with the data points.
NatashaNatashaThu, 04 Apr 2013 11:49:56 -0500http://ask.sagemath.org/question/9989/shift picewise functionshttp://ask.sagemath.org/question/8433/shift-picewise-functions/Suppose I define a piecewise function f for example:
f = Piecewise([[(-infinity,1),1],[(1,+infinity),x]])
How to define the shifted function g with g(x) = f(x-2) for all x?
Or more generally: If h is another function. How to define $g = f\circ h$ in sage?sagefanThu, 03 Nov 2011 05:15:34 -0500http://ask.sagemath.org/question/8433/Piece-wise functions and plottinghttp://ask.sagemath.org/question/9377/piece-wise-functions-and-plotting/Hi,
I have a piece-wise defined function that I want to plot (and potentially do other symbolic stuff with) and I was wondering how to do this. The problem is that I am defining my function as a Python function:
<pre>def F(x,y):
if( x <= y ):
return x*y
return x+y
</pre>
So I am gluing together two pieces, and I would like to be able to do
<pre>(x,y) = var('x,y')
contour_plot( F(x,y), (x,0,1), (y,0,1) )</pre>
But the problem is that this only plots the second part. This occurs because x <= y evaluates as false (they are variables) and F(x,y) is always evaluated as x+y. In Mathematica there is the <b>Which</b> function that works on symbolic expression to make piece-wise definitions. Is there an equivalent in Sage? Is there another way to do this? If I had a function (say, <i>delta</i>) that just evaluated as 1 if the symbolic expression was true, and 0 if not, I could craft the function as:
<pre>F(x,y) = delta( x<=y ) * (x*y) + delta( x>y ) * (x+y)</pre>
But as it is, I think there is no way to do this. Is there?
Thanks a lot for your help,
EdgarEdgarTue, 02 Oct 2012 04:20:42 -0500http://ask.sagemath.org/question/9377/Plotting Piecewise functionhttp://ask.sagemath.org/question/8935/plotting-piecewise-function/I have a large piecewise function (with 180 equations), how do I plot this on sage? Thanks
heres a sample:
[(1234, 1234), 0.0], [(1234,
1234), 0.0020259319286871956*x + 2.5], [(1234, 1234),
0.0060777957860615869*x + 7.5], [(1234, 1234), 0.010129659643435977*x +
12.5], [(1234, 1244), 0.0156672069165316*x + 19.333333335], [(1244,
1254), 0.015541264738745977*x + 19.333333335], [(1254, 1264),
0.015417331208133968*x + 19.333333335], [(1264, 1274),
0.015295358651107592*x + 19.333333335], [(1274, 1312),
0.015175300890894815*x + 19.333333335], [(1312, 1312),
0.014735772358993898*x + 19.333333335], [(1312, 1312),
0.022103658536585365*x + 29.0]EllieSun, 29 Apr 2012 09:18:48 -0500http://ask.sagemath.org/question/8935/Defining a function and forcing max or min valuehttp://ask.sagemath.org/question/8896/defining-a-function-and-forcing-max-or-min-value/Hi,
Is it possible to define a funtion, say f, and have it be the maximum (or minimum) of another function and a constant?
Example (pseudo-script): if g(x)=log(abs(x)), let f(x)=g(x) if g(x)>0, and f(x)=0 for all g(x)<0
Thanks
N.C.sagembTue, 17 Apr 2012 02:08:11 -0500http://ask.sagemath.org/question/8896/Piecewise assumptions (for integration)http://ask.sagemath.org/question/8710/piecewise-assumptions-for-integration/All right, still with these integration problems, and I don't know all the subtleties of passing extra-arguments to Maxima (ok, I reckon that @kcrisman doesn't stop pointing out Maxima flags now and then when some expert uses them but some list would be very handy).
What I want is to integrate a function with the domain of integration broken into pieces. The problem is that the maxima engine requires different assumptions for each piece but an assumption seems to tie a variable globally.
**Example**: In fact, this example is still related to the [double integral thread over there](http://ask.sagemath.org/question/1077/symbolic-expectations-and-double-integrals). After a little but tedious pen and paper work, I could get rid of the absolute value by breaking the domain of integration into pieces but then I'm stuck again. Independently of my own shortcomings and maybe the hard nature of what I tried to compute, in my sense, the remaining problem causes are mainly twofold, we need to talk to Maxima (pass assumptions) and the assumption mechanisms in Sage are somehow weak.
This is what I tried to get around these shortcomings and to answer the above question:
# This could take extra-arguments for the integral function (algorithm, ...) but I don't know all of them, so let's leave this as is for now.
def integral_assumptions(f, var, lbound, ubound, extra_assumptions):
old_assumptions= assumptions() # Keep current assumptions for later restore
assume(extra_assumptions)
result = integral(f, var, lbound, ubound)
forget()
assume(old_assumptions) # Unfortunately, extra assumptions don't stay local
return result
Different problems arise:
1- If the integral call breaks (and this often occurs), the old_assumptions are not restored .. ok, this one should be easy and dealt with some exception handling but I don't know the Sage coding guideline here.
x,y,u,v,p,k,b=var('x,y,u,v,p,k,b') # It seems enough to just say var('x,y,u,v,p,k,b') but I'm not sure
n(x)=1/sqrt(2*pi) * exp(-1/2*x^2) # I would have loved to be able to get this directly from Maxima but okay, it was just a few keystrokes away.
# I need to split at -sqrt(k-1)*v
alpha_neg(v,k,p)=integral_assumptions((u)^p*(u+sqrt(k-1)*v)^p*n(v)*n(u), u, 0, -sqrt(k-1)*v, [k-1 > 0, v < 0])
integral(alpha_neg(v, k, p), v, -oo, 0) # Error
alpha_neg(v,k,2) # Still an error but just to find the culprit
2- One **big** problem is the way Sage handles assumptions: they are global and (but maybe that *feature* is because of the fact that ...) they can't be made more stringent. Namely `assume(x>=0); assume(x>0)` doesn't yield x>0. It would have also been handy to be able to say forget(x>0) and it would give back x>=0 and have a forget_about(x) function which forgets everything about x ..
To be clear, I'm not against global assumptions but I just want some way to enforce extra assumptions locally.
3- Another bonus feature would have been the possibility of attaching a set of assumptions to an expression/function/whatnot. In fact I started with:
#inner_neg as we're on the part where v<0.
inner_neg(v, k, p, i_lo, i_hi)=integral_assumptions((u)^p*(u+sqrt(k-1)*v)^p*n(v)*n(u), u, i_lo, i_hi, v < 0)
g(v,k)=inner_neg(v, k, 1, 0, oo) # -sqrt(k-1)*v) # Ok with oo
If I instead ask with `-sqrt(k-1)*v`, Maxima again complains about vGreen diodSun, 12 Feb 2012 12:29:54 -0600http://ask.sagemath.org/question/8710/plot issue with a self-defined piecewise functionhttp://ask.sagemath.org/question/8643/plot-issue-with-a-self-defined-piecewise-function/The following code produces an error:
def f(x):
if x>3:
return(x^2)
if x<=3:
return(3*x)
plot(f(x),(x,0,5))
BUT, the code below works.
def f(x):
if x>3:
return(x^2)
if x<=3:
return(3*x)
plot(lambda x: f(x),(x,0,5))
So, my questions are:
(1) why do you need the lambda function? and
(2) when do you have to do this?
calc314Wed, 18 Jan 2012 09:10:48 -0600http://ask.sagemath.org/question/8643/find_fit piecewise defined functionshttp://ask.sagemath.org/question/8626/find_fit-piecewise-defined-functions/Hi all! I'm working with the function find_fit and now I need to fit a piecewise function, but I have tried it returns errors. How could I fit a picewise function?
ThanksEgrojSat, 14 Jan 2012 00:08:18 -0600http://ask.sagemath.org/question/8626/Piecewise functions and legend labelhttp://ask.sagemath.org/question/8495/piecewise-functions-and-legend-label/If I plot a piecewise function with a legend label like this:
plot(Piecewise([[(0,1),x],[(1,2),x^2]]),legend_label='f(x)')
I get the legend twice. Is there a way to ensure that it appears only one time, i.e. one legend for the whole function?sagefanSat, 19 Nov 2011 10:37:47 -0600http://ask.sagemath.org/question/8495/Animate plot of two piecewise functionshttp://ask.sagemath.org/question/8440/animate-plot-of-two-piecewise-functions/Consider a slightly modified version to the workaround to [this](http://ask.sagemath.org/question/868/two-piecewise-defined-functions-in-one-plot) question
sage: k = 5
sage: f = Piecewise([[(-2,1),k],[(1,4),x]])
sage: g = Piecewise([[(-2,1),1],[(1,4),2*x]])
sage: P = plot(f,color='green')
sage: Q = plot(g,linestyle='--')
sage: P+Q
Is it possible to animate this plot say with k ranging from 0 to 10?
I tried:
k = 5
f = Piecewise([[(-2,1),k],[(1,4),x]])
g = Piecewise([[(-2,1),1],[(1,4),2*x]])
P = plot(f,color='green')
Q = plot(g,linestyle='--')
X = P+Q
b = animate([X for k in srange(0,10)],xmin=0,xmax=4,figsize=[5,5])
b
b.show()
but it calculates for minutes and doesn't show up a result. (I tried examples from the documentation which worked fine).
I also tried this:
t = var('t')
k = var('k')
def f(t,k):
if t <=1:
return t
else:
return k
def g(t,k):
if t <=1:
return 1
else:
return 2*t
@interact
def _(k=(0,10)):
p1=plot(f(t,k),(t,0,3),ymax=10,ymin=0,color='green')
p2=plot(g(t,k),(t,0,3))
show(p1 + p2)
However the piecewise defined functions don't work in this case.sagefanFri, 04 Nov 2011 12:50:22 -0500http://ask.sagemath.org/question/8440/Plot every piece of a piecewise defined function in another color?http://ask.sagemath.org/question/8439/plot-every-piece-of-a-piecewise-defined-function-in-another-color/Is it possible to plot every piece of a piecewise defined function in another color?sagefanFri, 04 Nov 2011 12:32:05 -0500http://ask.sagemath.org/question/8439/