MPikkle - 1 year ago 44

Python Question

Is it possible to output a mathematical function directly from the function implementation ?

`class MyFunction:`

def __init__(self, func):

self.func = func

def math_representation(self):

# returns a string representation of self.func

f = lambda x: 3*x**2

myFunc = MyFunction(f)

print(myFunc.math_reprentation()) #prints something like 3*x**2

Of course constructing the object with the representation as a parameter is possible, and is a trivial solution. But the idea is to generate this representation.

I could also build the function with objects representing the math operations, but the idea is to do it on a regular (lambda) function.

I really don't see a way for this to happen, but I'm curious.

Thanks for any help and suggestion

Answer

As I said, you can use SymPy if you want this to be more complex, but for simple functions (and trusted inputs), you could do something like this:

```
class MathFunction(object):
def __init__(self, code):
self.code = code
self._func = eval("lambda x: " + code)
def __call__(self, arg):
return self._func(arg)
def __repr__(self):
return "f(x) = " + self.code
```

You can use it like this:

```
>>> sq = MathFunction("x**2")
>>> sq
f(x) = x**2
>>> sq(7)
49
```

This is a bit restricted, of course (only using the variable called "x", and only one parameter), but it can be, of course, expanded.

Source (Stackoverflow)