如何处理野性的结果

问题描述 投票:0回答:1

我有以下代码:

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

如何处理“野生”结果?如何不寻址数组,例如s [0],s {0}?

wildcard sympy
1个回答
0
投票

Wild可用于具有复杂计算结果的表达式,但您必须知道它的形式必须为sin(something)乘以something else。然后,s[q]将是“某物”的象征性表达。 s[p]代表“其他”。这可用于研究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并确定是否要使用相同的参数功效。

© www.soinside.com 2019 - 2024. All rights reserved.