'taking function as an input in SageMath
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.
Solution 1:[1]
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)
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samuel Lelièvre |
| Solution 2 | David Scholz |
