Ask Your Question

Handle variable name

asked 2015-03-30 08:41:21 -0500

Arnaud1418 gravatar image

updated 2015-03-30 08:44:55 -0500

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

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 flag offensive close merge delete

4 answers

Sort by ยป oldest newest most voted

answered 2015-03-30 11:06:31 -0500

updated 2015-03-30 11:07:13 -0500

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

In general, Sage comes with source, see Regarding the plot question, the triple is a standard Python tuple. I would need a more specific question to elaborate further.

edit flag offensive delete link more

answered 2015-03-30 11:01:47 -0500

tmonteil gravatar image

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))
edit flag offensive delete link more

answered 2015-03-30 13:15:49 -0500

this post is marked as community wiki

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)

f = z^2

Thanks to everyone for answers!

edit flag offensive delete link more

answered 2015-03-30 11:06:11 -0500

calc314 gravatar image

Here is a way to pass the triple you mentioned.

def f(*params):

show(f(interv) )
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

1 follower


Asked: 2015-03-30 08:41:21 -0500

Seen: 333 times

Last updated: Mar 30 '15