Ask Your Question
0

convert function to variable

asked 2014-08-29 17:39:49 +0100

Aloha,

I am solving differential equations using desolve, which requires that I declare my dependent variable, say y, as a function, but if I want to plot the result using implicit_plot or plot the slope field using plot_slope_field, then I need y to be a variable.

I have been able to do this by converting my function to a string, replacing "y(x)" by "y" and then converting the result back to a sage symbolic expression.

For example,

x = var('x')
y = function('y', x)
f=(4-2*x)/(3*y^2-5)
print(f)
y = var('y')
f=sage_eval(str(f).replace('y(x)','y'), locals=vars())
print(f)

prints

-2(x - 2)/(3y(x)^2 - 5)

-2(x - 2)/(3y^2 - 5)

An example with dsolve and implicit_plot:

# Define f(x,y)
x = var('x')
y = function('y', x)
f=(4-2*x)/(3*y^2-5)
# Define dy/dx=f(x,y)
de=diff(y,x)==f
# Solve dy/dx=f(x,y)
sol=desolve(de,y,ics=(1,3))
show(sol)
# Convert our solution to something that implicit_plot can handle,
# i.e., change y fom a function to a variable
y = var('y')
sol=sage_eval(str(sol).replace('y(x)','y'), locals=vars())
implicit_plot(sol, (x,-6,8), (y,-6,6))

I then wrote a function that does this:

def convert_function_to_var(f) :
    x,y = var('x,y')
    f=sage_eval(str(f).replace('y(x)','y'), locals=vars())
    return f

which I test this way

x = var('x')
y = function('y', x)
f=(4-2*x)/(3*y^2-5)
print(f)
f=convert_function_to_var(f)
print(f)

Now, my questions are

  1. is there a better way to do this?
  2. when I define convert_function_to_var why do I need to declare x,y = var('x,y') in the procedure?
  3. convert_function_to_var requires that I have two, and only two, variables, named x and y, is there some more generic and robust way of doing this?

Mahalo,

Ramón

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
1

answered 2014-08-29 18:53:23 +0100

tmonteil gravatar image

You can substitute instead of parsing a text representation.

sage: var('z')
z
sage: sol.subs(y(x)==z)
-1/2*z^3 + 5/2*z == 1/2*x^2 - 2*x - 9/2
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

Stats

Asked: 2014-08-29 17:39:49 +0100

Seen: 636 times

Last updated: Aug 29 '14