sympy - numpy conflict?

264 views
Skip to first unread message

Hans

unread,
Jul 20, 2008, 12:49:30 PM7/20/08
to sympy
At first: sympy is a great tool!
I'm a newbie and I tried the following code:

from sympy import *
x = symbols('x')
f = exp(-x)*sin(2*x)
e = diff(f,x)
print e

All worked well!
But adding a numpy import
an error message appeared:

from sympy import *
from numpy import *
x = symbols('x')
f = exp(-x)*sin(2*x)
e = diff(f,x)
print e

Traceback (most recent call last):
File "C:/Python25/discussion.py", line 6, in <module>
f = exp(-x)*sin(2*x)
AttributeError: exp

What happened? How could it be avoided?

Thanks!
Hans

Ondrej Certik

unread,
Jul 20, 2008, 1:17:50 PM7/20/08
to sy...@googlegroups.com
Hi Hans!

This is because you are mixing exp from numpy and from sympy. NumPy's
exp doesn't accept SymPy's symbols.

> How could it be avoided?

Use explicit imports, so that you see immediatelly what gets imported.
Or change the sympy and numpy import lines.

Ondrej

Gael Varoquaux

unread,
Jul 20, 2008, 1:17:57 PM7/20/08
to sy...@googlegroups.com
On Sun, Jul 20, 2008 at 09:49:30AM -0700, Hans wrote:
> from sympy import *
> from numpy import *
> x = symbols('x')
> f = exp(-x)*sin(2*x)
> e = diff(f,x)
> print e

> Traceback (most recent call last):
> File "C:/Python25/discussion.py", line 6, in <module>
> f = exp(-x)*sin(2*x)
> AttributeError: exp

> What happened?

When importing * from sympy you import "exp", and thus exp is defined as
something that knows about sympy symbols. Whereas when you import * from
numpy you also import "exp", but it is numpy's exp, that is an exp that
knows about arrays. You have overrided sympy's exp with numpy's exp.

> How could it be avoided?

It shouldn't be avoided. The only way to make numpy's exp and sympy's exp
to play well together would introduce cross-dependencies between numpy
and sympy, and we don't want to do that. What you should do is not mix
the namespaces: two differnet functions need to have a different name. In
Python you could do this like this:

from sympy import *
import numpy as np


x = symbols('x')
f = exp(-x)*sin(2*x)
e = diff(f,x)
print e

And remember that numpy function, such as exp, should be called using
"np.exp", rather than "exp".

HTH,

Gaël

Reply all
Reply to author
Forward
0 new messages