Loading [MathJax]/jax/output/HTML-CSS/jax.js
Ask Your Question
1

Show both sides of a function definition

asked 4 years ago

vinaypai gravatar image

When I define a function and show on it, I only get the right hand side. Is there a way to show the full definition? Basically I want to show pretty-printed version of the code used to define the function. I'm using a Jupyter notebook. I could simply rewrite it in a markdown cell of course, but that's tedious and error-prone my real use-case which is more complex than this toy example.

f(x) = a*x^2 + b*x + c
show(f)

What I get:

๐‘ฅ โ†ฆ ๐‘Ž๐‘ฅ2+๐‘๐‘ฅ+๐‘

What I want:

f(๐‘ฅ) = ๐‘Ž๐‘ฅ2+๐‘๐‘ฅ+๐‘

Preview: (hide)

1 Answer

Sort by ยป oldest newest most voted
3

answered 4 years ago

rburing gravatar image

The reason it works this way is technical; with the current implementation you cannot avoid it. The unfortunate fact is that the callable symbolic expression f doesn't know its own name. Namely, the code means the following:

sage: preparse("f(x) = a*x^2 + b*x + c")
'__tmp__=var("x"); f = symbolic_expression(a*x**Integer(2) + b*x + c).function(x)'

so f is only the name of the Python identifier, and the object that f refers to is an element of a CallableSymbolicExpressionRing, which only knows the names of its arguments.


As a workaround I suggest the following:

sage: show(LatexExpr('f(x) ='), f(x))

f(x)=ax2+bx+c

Yes, it involves repeating the name, but in my opinion it's not so bad.


You could also define this shorthand:

def show_func(func_str):
    func = sage_eval(func_str, globals())
    args = func.arguments()
    args_str = ','.join(str(arg) for arg in args)
    show(LatexExpr('{}({}) = '.format(func_str, args_str)), func(*args))

Then you can do:

sage: show_func('f')

f(x)=ax2+bx+c

(The argument has to be a string.)


Or maybe you'd like to use manifolds instead?

R.<x> = RealLine(latex_name=r'\mathbb{R}')
var('a,b,c')
f = R.scalar_field(a*x^2 + b*x + c, name='f')
show(f.display())

f:RโŸถRxโŸผax2+bx+c

That way you also get domains and codomains (and even more options).

Preview: (hide)
link

Comments

@rburing thank you for the detailed explanation and answer. You're right, repeating just the function name isn't too bad, so your suggestion does the trick.

vinaypai gravatar imagevinaypai ( 4 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

2 followers

Stats

Asked: 4 years ago

Seen: 503 times

Last updated: Jun 14 '20