ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Thu, 13 Jun 2013 22:26:03 +0200Please help me to draw f(x) = sin(x) if x<=0 and f(x)=cos(x) if x>1https://ask.sagemath.org/question/10226/please-help-me-to-draw-fx-sinx-if-x0-and-fxcosx-if-x1/thanks for your answers
Wed, 12 Jun 2013 14:33:24 +0200https://ask.sagemath.org/question/10226/please-help-me-to-draw-fx-sinx-if-x0-and-fxcosx-if-x1/Answer by calc314 for <p>thanks for your answers</p>
https://ask.sagemath.org/question/10226/please-help-me-to-draw-fx-sinx-if-x0-and-fxcosx-if-x1/?answer=15068#post-id-15068There are a few options. One is to use the `piecewise` command:
f=Piecewise([[(-10,1),sin(x)],[(1,10),cos(x)]],x)
plot(lambda x: f(x),(-2*pi,2*pi))
Another is to use a python function definition:
def f(x):
if x<=1:
return(sin(x))
else:
return(cos(x))
plot(f,(-2*pi,2*pi))
Note that with the python function definition, the `plot` command must be called just with `f` and not `f(x)`. Calling with `f(x)` causes python to evaluate $f$ before doing the plot and will result in an incorrect plot.Wed, 12 Jun 2013 15:50:39 +0200https://ask.sagemath.org/question/10226/please-help-me-to-draw-fx-sinx-if-x0-and-fxcosx-if-x1/?answer=15068#post-id-15068Comment by Eviatar Bach for <p>There are a few options. One is to use the <code>piecewise</code> command:</p>
<pre><code>f=Piecewise([[(-10,1),sin(x)],[(1,10),cos(x)]],x)
plot(lambda x: f(x),(-2*pi,2*pi))
</code></pre>
<p>Another is to use a python function definition:</p>
<pre><code>def f(x):
if x<=1:
return(sin(x))
else:
return(cos(x))
plot(f,(-2*pi,2*pi))
</code></pre>
<p>Note that with the python function definition, the <code>plot</code> command must be called just with <code>f</code> and not <code>f(x)</code>. Calling with <code>f(x)</code> causes python to evaluate $f$ before doing the plot and will result in an incorrect plot.</p>
https://ask.sagemath.org/question/10226/please-help-me-to-draw-fx-sinx-if-x0-and-fxcosx-if-x1/?comment=17504#post-id-17504More compactly, you could also use a lambda expression: `lambda x: sin(x) if x `<`= 1 else cos(x)`Thu, 13 Jun 2013 22:26:03 +0200https://ask.sagemath.org/question/10226/please-help-me-to-draw-fx-sinx-if-x0-and-fxcosx-if-x1/?comment=17504#post-id-17504Answer by John Palmieri for <p>thanks for your answers</p>
https://ask.sagemath.org/question/10226/please-help-me-to-draw-fx-sinx-if-x0-and-fxcosx-if-x1/?answer=15069#post-id-15069Another option is to use two separate plots: `plot(sin(x), (x, -10, 0)) + plot(cos(x), (x, 1, 10))`. By the way, I don't know if the question contains a typo or if there is not supposed to be a plot when x is between 0 and 1.Wed, 12 Jun 2013 20:01:21 +0200https://ask.sagemath.org/question/10226/please-help-me-to-draw-fx-sinx-if-x0-and-fxcosx-if-x1/?answer=15069#post-id-15069