4
votes
import numpy as np
import sympy as sym
from numpy import sin
from sympy import symbols, diff

func = lambda x: sin(x)
x    = symbols('x')
print diff(func(x),x)

This works if I replace my function with a polynomial, or if I place the trig function directly into the diff operator. But in this format I get AttributeError: sin.

Basically I think python can't recognize func as just being a trig function which it knows how to symbolically integrate. I could just have sympy import sin and then things would work, but then I'm stuck with func referencing sin in the sympy namespace and there are future things I want to do with func which require that it be defined using sin in the numpy namespace.

2
np.sinwon't accept sympy.core.symbol.Symbol and i doubt there are any sensible ways to make it so. Why are you trying to do this? - M4rtini
@M4rtini I want to plot func using matplotlib, and if func is defined using sin in the sympy namespace it causes an error. - Thoth

2 Answers

2
votes

You should build your expression up symbolically using SymPy functions, and then use lambdify to convert them into things that can be evaluated with NumPy.

0
votes

This simply isn't how you use sympy. You can't use normal functions in conjunction with numpy--you need to build symbolic expressions using the stuff it provides.

To write code to get the derivative of sin(x), you would do

import sympy as sym
from sympy import sin, symbols, diff

x = symbols('x')
print diff(sin(x), x)

If you have some other particular case you're having trouble with, you'll have to show it. You can't mix sympy with non-sympy stuff in this way, so there isn't some general feedback that can be provided.