【问题标题】:Sympy: prevent a subscripted symbol to be evaluatedSympy:防止评估下标符号
【发布时间】:2021-10-04 22:18:55
【问题描述】:

给定一个符号s,最终将是一个数组,我想定义以下表达式

A = Array([-s[1]/2, s[0]/2])

但我希望仅在计算包含它的其他一些表达式时才对 A 进行评估,因为 s 会随着时间而变化。我试过了

A = UnevaluatedExpr(Array([-s[1]/2,s[0]/2]))

但我收到了错误TypeError: 'Symbol' object is not subscriptable,这让我认为对s 执行了一些评估。

感谢您的耐心等待,我刚刚学习 Sympy,我已经习惯了 Maxima,这种构造很简单。更准确地说,使用 Maxima,我试图翻译到 Sympy 的完整工作代码是(在 Maxima 中,一切都是符号,冒号是赋值运算符,ev 强制使用自定义值进行评估, diff 之前的点是向量标量积):

A: [-s[2],s[1]]/2; /* define A in terms of subscripted symbols */
P1: [x1,y1];
P2: [x2,y2];
segment: P1+t*(P2-P1); /* --> [t*(x2-x1)+x1,t*(y2-y1)+y1] */
factor(integrate(ev(A,s=segment).diff(segment,t),t,0,1)); /* integrates the scalar product of A evaluated over segment and the derivative of segment */

跟进

感谢 Oscar 的回答,我能够对上述 Maxima 代码进行有效的 Sympy 翻译(欢迎改进!):

from sympy import *

def dotprod(*vectors): # scalar product, is there a built in better way?
    return sum(Mul(*x) for x in zip(*vectors))

s = IndexedBase('s')
A = Array([-s[1]/2,s[0]/2])

t,x1,y1,x2,y2 = symbols('t x1 y1 x2 y2')
P1 = Array([x1,y1])
P2 = Array([x2,y2])
segment = P1 + t * (P2-P1)

dotprod(A.subs(s,segment),segment.diff(t)).integrate((t,0,1)).factor()

除了IndexedBase magic,Maxima 和 Sympy 中的代码结构非常相似。

【问题讨论】:

    标签: sympy maxima


    【解决方案1】:

    我不确定我是否明白你想要什么。与使用Array 相比,以不同的方式解决您的问题可能会更好。无论如何,对您的问题的直接回答是您可以使用IndexedBase 来制作可下标符号:

    In [1]: s = IndexedBase('s')
    
    In [2]: A = Array([-s[1]/2, s[0]/2])
    
    In [3]: A
    Out[3]: 
    ⎡-s[1]   s[0]⎤
    ⎢──────  ────⎥
    ⎣  2      2  ⎦
    

    【讨论】:

    • 我用我要翻译的 Maxima 代码更新了我的问题,我希望它能阐明我想要做什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 2023-01-20
    • 2018-04-15
    • 1970-01-01
    相关资源
    最近更新 更多