Skip to content Skip to sidebar Skip to footer

Sympy - Is There A Way To Differentiate Over An Abstract Variable?

I'm learning SymPy now, and I wonder if there's a way to differentiate a function over one of its variables in the general form. Consider this example: There a vector, lets write i

Solution 1:

You can do this with IndexedBase. The result comes out in Kronecker delta functions which than simplify after substitution:

In [3]: x = IndexedBase('x')

In [4]: r = sqrt(x[1]**2 + x[2]**2 + x[3]**2)

In [5]: r
Out[5]: 
   _______________________
  ╱     2       2       2 
╲╱  x[1]  + x[2]  + x[3]  

In [6]: i = Symbol('i')

In [7]: r.diff(x[i])
Out[7]: 
δ   ⋅x[1] + δ   ⋅x[2] + δ   ⋅x[3]
 1,i         2,i         3,i     
─────────────────────────────────
       _______________________   
      ╱     2       2       2    
    ╲╱  x[1]  + x[2]  + x[3]     

In [8]: r.diff(x[i]).subs(i, 2)
Out[8]: 
           x[2]           
──────────────────────────
   _______________________
  ╱     2       2       2 
╲╱  x[1]  + x[2]  + x[3] 

You can also do this for a vector of symbolic dimension:

In [9]: j = Symbol('j')

In [9]: N = Symbol('N')

In [10]: r = sqrt(Sum(x[i]**2, (i, 1, N)))

In [10]: r
Out[10]: 
         _____________
        ╱   N         
       ╱   ___        
      ╱    ╲          
     ╱      ╲       2 
    ╱       ╱   x[i]  
   ╱       ╱          
  ╱        ‾‾‾        
╲╱        i = 1       

In [11]: r.diff(x[j])
Out[11]: 
     N                  
    ___                 
    ╲                   
     ╲   2⋅δ   ⋅x[i]    
     ╱      i,j         
    ╱                   
    ‾‾‾                 
   i = 1                
────────────────────────
           _____________
          ╱   N         
         ╱   ___        
        ╱    ╲          
       ╱      ╲       22⋅    ╱       ╱   x[i]  
     ╱       ╱          
    ╱        ‾‾‾        
  ╲╱        i = 1       

In [12]: r.diff(x[j]).subs(N, 3).subs(j, 2)
Out[12]: 
     3                  
    ___                 
    ╲                   
     ╲   2⋅δ   ⋅x[i]    
     ╱      2,i         
    ╱                   
    ‾‾‾                 
   i = 1                
────────────────────────
           _____________
          ╱   3         
         ╱   ___        
        ╱    ╲          
       ╱      ╲       22⋅    ╱       ╱   x[i]  
     ╱       ╱          
    ╱        ‾‾‾        
  ╲╱        i = 1       

In [13]: r.diff(x[j]).subs(N, 3).subs(j, 2).doit()
Out[13]: 
           x[2]           
──────────────────────────
   _______________________
  ╱     222 
╲╱  x[1]  + x[2]  + x[3]  

Post a Comment for "Sympy - Is There A Way To Differentiate Over An Abstract Variable?"