Sympy:如何将产品的对数简化为对数之和?

时间:2017-09-20 09:14:27

标签: python sympy

为了激发这个问题,sympy.concrete有一些有效的工具来操纵符号总和。为了将这些工具应用于符号产品,必须采用对数。但是,直接取对数并不会自动进行转换:

import sympy as sp
sp.init_printing() # display math as latex
z = sp.Symbol('z')
j,k = sp.symbols('j,k')
Prod = sp.Product( (z + sp.sqrt(1-4*j*z**2))**(-1), (j,1,k) )
sp.log(Prod)

给出

\log{\left (\prod_{j=1}^{k} \frac{1}{z + \sqrt{- 4 j z^{2} + 1}} \right )}

所有可能的变体:

sp.log(Prod)
sp.log(Prod).expand()
sp.log(Prod).simplify()
sp.expand_log(sp.log(Prod),force=True)
  

问题即可。如何将其转换为对数之和?

相关:

How to simplify logarithm of exponent in sympy?

1 个答案:

答案 0 :(得分:2)

假设没有所需行为的标准功能,我自己编写,模仿

的行为
sp.expand_log(expr, force=True)

此代码以递归方式覆盖表达式,尝试查找模式log(product)并将其替换为sum(log)。这也支持多索引求和。

  

<强>代码。

def concrete_expand_log(expr, first_call = True):
    import sympy as sp
    if first_call:
        expr = sp.expand_log(expr, force=True)
    func = expr.func
    args = expr.args
    if args == ():
        return expr
    if func == sp.log:
        if args[0].func == sp.concrete.products.Product:
            Prod = args[0]
            term = Prod.args[0]
            indices = Prod.args[1:]
            return sp.Sum(sp.log(term), *indices)
    return func(*map(lambda x:concrete_expand_log(x, False), args))
  

示例

import sympy as sp
from IPython.display import display
sp.init_printing() # display math as latex
z = sp.Symbol('z')
j,k,n = sp.symbols('j,k,n')
Prod = sp.Product( (z + sp.sqrt(1-4*j*z**2))**(-1), (j,0,k))
expr = sp.log(z**(n-k) * (1 - sp.sqrt((1 - 4*(k+2)*z**2)/(1-4*(k+1)*z**2)) ) * Prod)
display(expr)

\log{\left (z^{- k + n} \left(- \sqrt{\frac{- z^{2} \left(4 k + 8\right) + 1}{- z^{2} \left(4 k + 4\right) + 1}} + 1\right) \prod_{j=0}^{k} \frac{1}{z + \sqrt{- 4 j z^{2} + 1}} \right )}

display(concrete_expand_log(expr))

\left(- k + n\right) \log{\left (z \right )} + \log{\left (- \sqrt{\frac{- z^{2} \left(4 k + 8\right) + 1}{- z^{2} \left(4 k + 4\right) + 1}} + 1 \right )} + \sum_{j=0}^{k} \log{\left (\frac{1}{z + \sqrt{- 4 j z^{2} + 1}} \right )}