ajujuz
ajujuz

Reputation: 41

The diff function in sympy doesn't return a number?

I'm a newbie learning python. I have a question, can you guys help me? This is my code:

from sympy import *
def test(f, g, a):
   f1 = f.subs(x, g)
   df1 = diff(f1, x).subs(x, a)
   return df1
print(test((2*(x**2) + abs(x + 1)), (x - 1), -1))

Result: -Subs(Derivative(re(x), x), x, -1) - 8

I'm taking the derivative of f(g(x)) with: f = 2(x^2) + abs(x + 1), g = x - 1 and x = -1. When I use diff to calculate the result is -Subs(Derivative(re(x), x), x, -1) - 8, but when I use the formula lim x->x0 (f(x) - f(x0))/(x - x0) I got result is -9. I also tried using a calculator to calculate and the result -9 is the correct result. Is there a way to make diff return -9? Anyone have any help or can give some pointers?

Thanks!

Upvotes: 4

Views: 291

Answers (2)

smichr
smichr

Reputation: 19029

Whenever I see a re or im appear when I didn't expect them, I am inclined to make the symbols real:

>>> from sympy import *
>>> def test(f, g, a):
...    f1 = f.subs(x, g)
...    df1 = diff(f1, x).subs(x, a)
...    return df1
...
>>> var('x',real=True)
x
>>> print(test((2*(x**2) + abs(x + 1)), (x - 1), -1))
-9

Upvotes: 3

hpaulj
hpaulj

Reputation: 231385

Since I'm still a relative beginner to sympy I like to view intermediate results (I even like to do that with numpy which I know much better). Running in isympy:

In [6]: diff(f1,x)
Out[6]: 
          ⎛      d                 d        ⎞        
          ⎜re(x)⋅──(re(x)) + im(x)⋅──(im(x))⎟⋅sign(x)
          ⎝      dx                dx       ⎠        
4⋅x - 4 + ───────────────────────────────────────────
                               x      

That expression contains unevaluate d/dx and the distinction between the real and imaginary parts of x.

Restricting x to real as suggested in the other answer produces:

In [19]: diff(exp,x)
Out[19]: 4⋅x + sign(x + 1)

Upvotes: 1

Related Questions