且构网

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

Symify 改变一切的顺序

更新时间:2023-01-24 20:00:09

您没有在 ns 中包含 B,所以 b 符号是由 sympify 自动创建的作为交换符号(顺便说一下,您也从未定义过 e_1).

You didn't include B in your ns, so the b symbols were created by sympify automatically as commutative Symbols (you also never defined e_1 by the way).

我建议您的流程更干净,以避免出现这样的问题:

I recommend being cleaner with your processes to avoid issues like this:

  • 在数字后缀前与 _ 保持一致,而不要与 _ 保持一致.在任何地方都使用 a_0 或 a0 .

  • Be consistent with _ vs no _ before numeric suffixes. Either use a_0 or a0 everywhere.

将变量命名为与符号名称相同的名称.

Name your variables the same as the symbol names.

如果你在执行时有你的字符串,不要使用sympify.相反,只需定义您的符号名称并将字符串作为表达式执行 (expr = e0*((d0*a_00)*(-e1...).这样,如果出现以下情况,Python 会自动警告您您有未定义的符号名称.

If you have your string at execution time, don't use sympify. Rather, just define your symbol names and execute the string as an expression (expr = e0*((d0*a_00)*(-e1...). This way, Python will automatically warn you if you have undefined symbol names.

如果你必须解析字符串,你可以使用parse_expr来避免自动符号定义:

If you do have to parse strings, you can avoid automatic symbol definition by using parse_expr:

from sympy.parsing.sympy_parser import parse_expr, standard_transformations, auto_symbol

transformations = list(standard_transformations)
transformations.remove(auto_symbol)

parse_expr('a*b', local_dict={'a': Symbol('a', commutative=False)}, transformations=transformations)

注意这会导致关于 b 未被定义的错误,而不是仅仅将其定义为一个可交换符号.

Note how this gives an error about b not being defined, rather than just defining it as a commutative Symbol.