[英]How to make user-input for Symbols case insensitive
我想避免在我制作的scypy基本腳本中出現大寫鎖定錯誤。 腳本計算偏導數
from sympy import *
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, \
x, y, z = symbols('x y z ', real=True)
transformations = (standard_transformations + (implicit_multiplication_application,)
self.eq1 = parse_expr(self.entry_5.get(), locals(), transformations=transformations)
self.dfx = diff(self.eq1, x)
self.dfy = diff(self.eq1, y)
self.dfz = diff(self.eq1, z)
對於這個例子 entry_5 工作正常是 x ** 2 + y ** 2 + z ** 2
'Partial derivatives calculation:
Partial der by X: 2*x
Partial der by Y: 2*y
Partial der by Z: 2*z
但現在,我正在嘗試使用相同的代碼添加大寫 X、Y、Z:
.
.
.
x, y, z, X, Y, Z = symbols('x y z X Y Z', real=True)
.
.
.
現在,entry_5 是- X ** 2 + y ** 2 + z ** 2 (大寫 x)和 output 是:
'Partial derivatives calculation:
Partial der by X: 0
Partial der by Y: 2*y
Partial der by Z: 2*z
如果您希望將輸入重新轉換為小寫,以便您硬編碼的導數始終有效,您可以將輸入轉換為小寫,或者更安全地提供將感興趣的大寫符號重新映射為小寫符號的locals
變量。 為了清楚起見,我使用S
來表示而不是解析器:
>>> S('x', {'x':'upper'}) # example showing you can replace 'x' with 'upper'
upper
>>> S('X', dict([(str(i), str(i).lower()) for i in symbols('X:Z')]))
x
在您的代碼中,您必須使用我的示例中使用的 dict() 更新您的本地人: loc = locals(); loc.update(dict([(str(i), str(i).lower()) for i in symbols('X:Z')]))
loc = locals(); loc.update(dict([(str(i), str(i).lower()) for i in symbols('X:Z')]))
並在代碼中使用loc
而不是locals()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.