Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
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!

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report

0

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)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!