# Handle variable name

Dear all,

I would like to pass a function as a parameter and also one of its variable. The simplest situation would just to evaluate a function f.

def test(f,myvar,myval):
return f(myvar=myval)

f = x^2
print(test(f,x,3)


It returns x^2, but I would like 9. Of course I don't know a priori what would be the name of the variable and f may have several variables.

The long question is that I would like to define something that plot(f,(x,xmin,xmax)). Is there's a standard way to handle this triple (x,xmin,xmax)? Is there's a web page for the source code for such functions to study the standard implementation?

Thanks a lot! Arnaud

edit retag close merge delete

Sort by » oldest newest most voted

As to the first question, use subs:

sage: def test(f,myvar,myval):
return f.subs(myvar==myval)
....:
sage: f = x^2
sage: print(test(f,x,3))
9


In general, Sage comes with source, see https://github.com/sagemath/sage Regarding the plot question, the triple is a standard Python tuple. I would need a more specific question to elaborate further.

more

You could try with passing a dictionary to the .subs() method:

sage: def test(f,myvar,myval):
sage:    return f.subs({myvar:myval})

sage: print(test(f,x,3))
9

more

Here is a way to pass the triple you mentioned.

def f(*params):
p=plot(x^2,*params)
return(p)

interv=(x,-3,3)
show(f(interv) )

more This post is a wiki. Anyone with karma >750 is welcome to improve it.

Compiling the answers above, here is a simple mean value function taking as parameters (i) a function and (ii) a triple defining the variable and the min and max values.

def meanvalue(f,mytriple):
myvar,mymin,mymax = mytriple
return f.subs(myvar==(mymin+mymax)/2)

var('z')
f = z^2
meanvalue(f,(z,0,1))


more