1

I want to convert a function defined in Python to a symbolic expression in SymPy (lambdify does the opposite):

import numpy as np
import sympy as sp

def fun1(t):
  return t + 3

def fun2(t):
  return np.sin(t)

And then convert this fun1 and fun2 to a symbolic expression so I can do, for example:

x = sp.symbols('x')
fun1s = fun1(x)
fun2s = fun2(x)

Then I can differentiate them like:

dfun1s = sp.diff(fun1s, x)
dfun2s = sp.diff(fun2s, x)

I found something here but it's quite complicated, is there an easier way to do it?

Matt Hall
  • 7,614
  • 1
  • 23
  • 36
Tito Diego
  • 47
  • 1
  • 6
  • 3
    What you're asking for is, in fact, a complicated question. – Iguananaut Jul 28 '21 at 16:59
  • If you want to work with symbolic math in Python you may find [SageMath](https://www.sagemath.org/) useful. However, it also does not have a way to convert an arbitrary Python function (especially if you're using calls like `np.something`) to a symbolic function. – Iguananaut Jul 28 '21 at 17:00
  • I thought that how you can easily do the opposite with lambdify, there would be a easy way to do it – Tito Diego Jul 28 '21 at 17:07
  • Not at all. One is taking an existing [expression tree](https://en.wikipedia.org/wiki/Binary_expression_tree) of a fixed set of operators and functions and producing something that evaluates the expression on an input. The other is parsing and constructing something out of arbitrary Python code. There are projects which do this for the sake of efficient numerical evaluation, like Numba, but these are extraordinarily complicated. – Iguananaut Jul 28 '21 at 17:11
  • Yes that works, I was looking for something easier to deal with, but seems to be very complicated @kwinkunks – Tito Diego Jul 28 '21 at 17:38
  • Functions are parsed by the interpreter. `introspection` tells you about arguments, but (usually) not about code details. `sympy` expressions have a tokenized tree structure more like the source (and may be parsed from a string). `lambdify` is a relatively simple lexical translation. Look at the `help` of a lambdified function. – hpaulj Jul 30 '21 at 00:42

0 Answers0