Ask Your Question
0

Handle variable name

asked 10 years ago

Arnaud1418 gravatar image

updated 10 years ago

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

Preview: (hide)

4 Answers

Sort by » oldest newest most voted
0

answered 10 years ago

rws gravatar image

updated 10 years ago

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.

Preview: (hide)
link
1

answered 10 years ago

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))
9
Preview: (hide)
link
0

answered 10 years ago

calc314 gravatar image

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) )
Preview: (hide)
link
0

answered 10 years ago

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)

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

Thanks to everyone for answers!

Preview: (hide)
link

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

Stats

Asked: 10 years ago

Seen: 1,403 times

Last updated: Mar 30 '15