Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

taking function as an input in SageMath

Tags:

sage

How do you make a function that takes a function as input? What I want to do is something like:

f(x) = log(x)
g(f, x) = x^2 * f(x)

g(f, 2) 
# Symbolic expression of x^2 * log(x)

I think I am looking for the way to create higher order function.

like image 223
Ikuyasu Avatar asked Oct 24 '25 17:10

Ikuyasu


2 Answers

Would using a lambda function for g work for you?

Here is a way to do that:

sage: f(x) = log(x)
sage: g = lambda u, v: v*2 * u(v)
sage: g(f, 2)
4*log(2)
like image 157
Samuel Lelièvre Avatar answered Oct 28 '25 04:10

Samuel Lelièvre


We can create a python function that returns a symbolic function and takes two symbolic functions as an input.

Consider the following code.

g(x) = x^2
f(x) = log(x)

def foo(f, g, x):
    return g(x) * f(x)

z(x)=foo(g, f, x)

Take a look at it.

sage: z

which yields to the symbolic function

x |--> x^2*log(x)
like image 42
David Scholz Avatar answered Oct 28 '25 03:10

David Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!