且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

sympy - 有没有办法区分抽象变量?

更新时间:2023-02-25 14:34:48

您可以使用 IndexedBase 做到这一点.结果出现在 Kronecker delta 函数中,该函数在替换后进行了简化:

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         
         ╱   ___        
        ╱    ╲          
       ╱      ╲       2 
2⋅    ╱       ╱   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         
         ╱   ___        
        ╱    ╲          
       ╱      ╲       2 
2⋅    ╱       ╱   x[i]  
     ╱       ╱          
    ╱        ‾‾‾        
  ╲╱        i = 1       

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