如何使用 wild sympy 的结果

How to work with the result of the wild sympy

我有以下代码:

f=tan(x)*x**2
q=Wild('q')
s=f.match(tan(q))
s={q_ : x}

如何处理 "wild" 的结果?如何不对数组进行寻址,例如s[0], s{0}?

Wild 当你有一个表达式是一些复杂计算的结果时,可以使用

Wild,但你知道它必须是 sin(something) 乘以 something else 的形式。然后 s[q] 将是 "something" 的 sympy 表达式。而 s[p] 为 "something else"。这可用于调查 p 和 q。或者进一步使用 f 的简化版本,用新变量替换 p 和 q,尤其是当 p 和 q 是涉及多个变量的复杂表达式时。

更多的用例是可能的。

这是一个例子:

from sympy import *
from sympy.abc import x, y, z

p = Wild('p')
q = Wild('q')
f = tan(x) * x**2
s = f.match(p*tan(q))
print(f'f is the tangent of "{s[q]}" multiplied by "{s[p]}"')
g = f.xreplace({s[q]: y, s[p]:z})
print(f'f rewritten in simplified form as a function of y and z: "{g}"')
h = s[p] * s[q]
print(f'a new function h, combining parts of f: "{h}"')

输出:

f is the tangent of "x" multiplied by "x**2"
f rewritten in simplified form as a function of y and z: "z*tan(y)"
a new function h, combining parts of f: "x**3"

如果您对 tan 中作为产品出现在 f 中的所有参数感兴趣,您可以尝试:

from sympy import *
from sympy.abc import x

f = tan(x+2)*tan(x*x+1)*7*(x+1)*tan(1/x)

if f.func == Mul:
    all_tan_args = [a.args[0] for a in f.args if a.func == tan]
    # note: the [0] is needed because args give a tupple of arguments and
    #   in the case of tan you'ld want the first (there is only one)
elif f.func == tan:
    all_tan_args = [f.args[0]]
else:
    all_tan_args = []

prod = 1
for a in all_tan_args:
    prod *= a

print(f'All the tangent arguments are: {all_tan_args}')
print(f'Their product is: {prod}')

输出:

All the tangent arguments are: [1/x, x**2 + 1, x + 2]
Their product is: (x + 2)*(x**2 + 1)/x

请注意,这两种方法都不适用于 f = tan(x)**2。为此,您需要再写一个 match 并决定是否要对参数进行相同的处理。