Is there a way to expand polynomials using Sympy?
Looking at the Sympy documentation, there seems to be an "expand" function which can be called upon to expand polynomial expressions; however, in practice, this is not working for me. I started off using imaginary numbers:
import sympy sympy.expand((x - 1)(x + i)(x - i))
Hoping for "x^3 – x^2 + x – 1", however, instead, this returned the following error: module ‘sympy’ has no attribute ‘expand’
I then changed the expression I wanted to be expanded, as this had caused me to assume that Sympy could not handle complex numbers, to what can be seen below:
import sympy sympy.expand((x - 1)(x - 1)(x + 1))
Yet this returned the same error.
The imaginary i
is represented by the capital I
in sympy. To have a multiplication, an *
needs to be used explicitly. Also, in Python ^
is strictly reserved for a boolean (or bitwise) exclusive or. Power is represented as **
.
from sympy import symbols, I, expand x = symbols('x') print(expand((x - 1)*(x + I)*(x - I)))
Output: x**3 - x**2 + x - 1
Note that an alternative way to call expand()
is as expression.expand()
(or ((x - 1)*(x + I)*(x - I)).expand()
as in the example). Often this is a handy way to concatenate several operations.
I don’t have problem to run
import sympy x = sympy.Symbol('x') i = sympy.Symbol('i') sympy.expand( (x - 1)*(x + i)*(x - i) )
and this gives me
-i**2*x + i**2 + x**3 - x**2
The only idea: you created file with name sympy.py
and now import sympy
loads your file instead of module sympy
and it can’t find expand
in your file. You have to rename your file sympy.py
to something different (which is not name of other module).
But you didn’t add full error message in question so I can’t confirm it.