【问题标题】:Replacing composed functions in Sympy替换 Sympy 中的组合函数
【发布时间】:2018-07-26 21:04:52
【问题描述】:

我正在尝试以f(g(x)) 的形式生成一些随机表达式。我希望能够将g 替换为sin(x)x**2f 之类的cos(x)log(x)。所以我会得到类似sin(cos(x))log(x**2) 的东西(但随机)。

我遇到问题的部分任务是同时替换外部函数和内部函数。

这是我的代码:

import sympy
from sympy import abc

x = abc.x
f = sympy.Function('f')(x)
g = sympy.Function('g')(x)

full=f.subs(x, g)
newExpr = sympy.sin(x)
newExpr2 = sympy.cos(x)

print(full)

replaced_inner = full.subs(g, newExpr)
print(replaced_inner)

both = replaced_inner.subs(f, newExpr2)
print(both)

full 打印 f(g(x)) 以便工作
replaced_inner 打印 f(sin(x)) 以便同样工作
both 打印 f(sin(x)) 当我希望它打印 cos(sin(x))

我尝试过使用args[0]f.func,但没有取得任何进展。

如何替换内部函数和外部函数(以及最终更复杂的内容,例如 f(g(h(x)))

我可以简单地创建cos(sin(x)),但我想使用变量来创建它,这样我就可以随机化要替换的函数。

【问题讨论】:

    标签: python sympy


    【解决方案1】:

    问题在于sympy.Function('f')函数sympy.Function('f')(x)表达式 混淆。定义 f = sympy.Function('f')(x) 后,您将 f 设为表达式 f(x)。而且因为 表达式 f(g(x)) 没有 f(x) 作为子表达式,尝试替换失败。

    如果您使用实际功能,所有这些都已修复,而不是过早插入 x

    f = sympy.Function('f')
    g = sympy.Function('g')
    
    full = f(g(x))
    newExpr = sympy.sin
    newExpr2 = sympy.cos
    
    print(full)
    
    replaced_inner = full.subs(g, newExpr)
    print(replaced_inner)
    
    both = replaced_inner.subs(f, newExpr2)
    print(both)
    

    打印出来

    f(g(x))
    f(sin(x))
    cos(sin(x))
    

    除此之外:您可能还对支持某些模式的replace 方法感兴趣。此处不需要,但对于更高级的替换可能是必需的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多