# Animate plot of two piecewise functions

Consider a slightly modified version to the workaround to this 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.

edit retag close merge delete

Sort by » oldest newest most voted

Ok, this should work.

sage: f = lambda k: Piecewise([[(-2,1),k],[(1,4),x]])
sage: P = plot(f(5))
sage: show(P)
KeyboardInterrupt
sage: A = animate([plot(f(k)) for k in [0..10]])
sage: show(A)


Hopefully something similar would work in an interact...

If you've never seen them, then lambda functions are mysterious, but it turns out useful for exactly this kind of thing.

I think this is probably the only reasonable way to do it, since piecewise functions automatically treat any variable in them as the function inside.

sage: var('y,z')
(y, z)
sage: g = Piecewise([[(-2,1),y^2],[(1,4),-z^2]])
sage: plot(g)

more

Probably. Have you tried looking at

sage: animate?


and

sage: interact?


(the latter only works in the notebook). I would think one or both of these should work just fine.

Edit after update of question:

The first example will never work because of how Python handles variables.

sage: k = 5
sage: f = Piecewise([[(-2,1),k],[(1,4),x]])
sage: f
Piecewise defined function with 2 parts, [[(-2, 1), 5], [(1, 4), x]]


So k just slapped a 5 in there.

Let me try to see if I can come up with a workaround...

more