Ask Your Question

Animate plot of two piecewise functions

asked 2011-11-04 18:50:22 +0200

sagefan gravatar image

updated 2011-11-05 05:08:17 +0200

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])

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
        return k

def g(t,k):
    if t <=1:
        return 1
        return 2*t

def _(k=(0,10)):
    show(p1 + p2)

However the piecewise defined functions don't work in this case.

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2011-11-05 22:26:16 +0200

kcrisman gravatar image

Ok, this should work.

sage: f = lambda k: Piecewise([[(-2,1),k],[(1,4),x]])
sage: P = plot(f(5))
sage: show(P)
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)
edit flag offensive delete link more


Ok, thanks. It works in both cases.

sagefan gravatar imagesagefan ( 2011-11-06 08:28:46 +0200 )edit

answered 2011-11-04 23:04:49 +0200

kcrisman gravatar image

updated 2011-11-05 22:18:30 +0200

Probably. Have you tried looking at

sage: animate?


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...

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2011-11-04 18:50:22 +0200

Seen: 858 times

Last updated: Nov 05 '11