Johiasburg Frowell
Johiasburg Frowell

Reputation: 588

Why does sympy.diff not differentiate sympy polynomials as expected?

I am trying to figure out why sympy.diff does not differentiate sympy polynomials as expected. Normally, sympy.diff works just fine if a symbolic variable is defined and the polynomial is NOT defined using sympy.Poly. However, if the function is defined using sympy.Poly, sympy.diff does not seem to actually compute the derivative. Below is a code sample that shows what I mean:

import sympy as sy

# define symbolic variables
x = sy.Symbol('x')
y = sy.Symbol('y')

# define function WITHOUT using sy.Poly
f1 = x + 1
# define function WITH using sy.Poly
f2 = sy.Poly(x + 1, x, domain='QQ')

# compute derivatives and return results
df1 = sy.diff(f1,x)
df2 = sy.diff(f2,x)
print('f1:  ',f1)
print('f2:  ',f2)
print('df1:  ',df1)
print('df2:  ',df2)

This prints the following results:

f1:   x + 1
f2:   Poly(x + 1, x, domain='QQ')
df1:   1
df2:   Derivative(Poly(x + 1, x, domain='QQ'), x)

Why does sympy.diff not know how to differentiate the sympy.Poly version of the polynomial? Is there a way to differentiate the sympy polynomial, or a way to convert the sympy polynomial to the form that allows it to be differentiated?

Note: I tried with different domains (i.e., domain='RR' instead of domain='QQ'), and the output does not change.

Upvotes: 4

Views: 2089

Answers (1)

ptb
ptb

Reputation: 2148

This appears to be a bug. You can get around it by calling diff directly on the Poly instance. Ideally calling the function diff from the top level sympy module should yield the same result as calling the method diff.

In [1]: from sympy import *

In [2]: from sympy.abc import x

In [3]: p = Poly(x+1, x, domain='QQ')

In [4]: p.diff(x)
Out[4]: Poly(1, x, domain='QQ')

In [5]: diff(p, x)
Out[5]: Derivative(Poly(x + 1, x, domain='QQ'), x)

In [6]: diff(p, x).doit()
Out[6]: Derivative(Poly(x + 1, x, domain='ZZ'), x)

Upvotes: 5

Related Questions