using python function within desolve_odeint

131 views
Skip to first unread message

Jeff Denny

unread,
Feb 25, 2014, 1:25:52 PM2/25/14
to sage-s...@googlegroups.com
My students are attempting to use a python function with an if statement in it as part of a differential equation they are solving with desolve_odeint. Unfortunately, of course, Sage executes the python function as soon as they write it and not within the solver. I need help on getting around this. Here is some same code for a simpler case than what they are doing.


def f(x,y):
if x<0.2:
return(0)
else:
return(y*(1-y))

ans=desolve_odeint([SR(1),f(x,y)],[0,0.5],srange(0,10,0.01),[x,y])

Jason Grout

unread,
Feb 26, 2014, 5:13:42 PM2/26/14
to sage-s...@googlegroups.com
I'll note that my first reaction, to call desolve_odeint with just f
instead of f(x,y), gives an error about f not having a variables method:

http://sagecell.sagemath.org/?q=zmmcru

Jason


Jeff Denny

unread,
Feb 26, 2014, 9:18:26 PM2/26/14
to sage-s...@googlegroups.com
I've gone back to the basics.  The keys seem to be to define the independent variable, to write both components of the vector field as functions but not to specify the inputs to the functions in the vector field definition, and (most critically) to use the parameter identifiers (ivar, dvars, time, ics) in the call to desolve_odeint.

The following code seems to be working now.

var('x y t')

def dx(x,y,t):
    if x<0.2:
        return(-x)
    else:
        return(y*(1-y))

def dy(x,y,t):
    return(1)

F=[dx,dy]

ans=desolve_odeint(F,ics=[0.5,1],times=srange(0,10,0.1),dvars=[x,y],ivar=t)
line(ans)


Reply all
Reply to author
Forward
0 new messages