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.Fri, 29 Aug 2014 17:39:49 +0200convert function to variablehttps://ask.sagemath.org/question/23984/convert-function-to-variable/ 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)/(3*y(x)^2 - 5)
-2*(x - 2)/(3*y^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ónRamón Figueroa-CentenoFri, 29 Aug 2014 17:39:49 +0200https://ask.sagemath.org/question/23984/