Sympy通过平方倍简化不等式

时间:2018-12-04 17:08:41

标签: python sympy

我有一个不等式,其中充斥着对实值变量具有先验积极性的因素。如果我能对自己“与他们打交道”感到很高兴。

例如:

import sympy
x,y = sympy.symbols('x y')
sympy.simplify((x**2 + 1)*y > 0)
# (x**2+1)*y > 0 (sympy does nothing)

现在,很明显(x**2+1)*y > 0与{{1}相对,因为y>0对真实(x**2+1)总是正的。换句话说,一些简化此类事情的合理功能可能会赋予:

x

是否有一个sympy函数可以简化这些事情?

请注意,以上只是一个简单的示例,我一般不会只想解决simplify_positive_terms((x**2+1)*y > 0) # y > 0

1 个答案:

答案 0 :(得分:1)

这是我想出的:

import sympy

def simplify_inequality(e):
    ''' 
    Assume e is an instance of either one of the following:
    sympy.core.relational.StrictGreaterThan
    sympy.core.relational.GreaterThan
    sympy.core.relational.StrictLessThan
    sympy.core.relational.LessThan

    Also, assume that the e is an inequality of the form Mul(f,g..,z) > 0

    '''
    lefthand_side = e.args[0]
    righthand_side= e.args[1]
    if not isinstance(lefthand_side,sympy.mul.Mul):
        return e

    multiplicands = lefthand_side.args
    needed_factors = []
    for factor in multiplicands:
        if len(factor.free_symbols) != 1: # if it has more than one variable, don't try to simplify
            needed_factors.append(factor)

        else:
            result_set = sympy.solveset(factor,factor.free_symbols.pop(),sympy.S.Reals) # see if there are any solutions over the reals   
            if not result_set.is_EmptySet: # there are solutions, this factor is can't be simplified
                needed_factors.append(factor)
            else:    
                free_sym = factor.free_symbols.pop()
                if factor.subs(free_sym,0) > 0: # ok, this factor is always positive, it can go away
                    pass
                else: # we still need it
                    needed_factors.append(factor)

    new_lefthand_side = sympy.mul.Mul(*needed_factors)
    return e.func(*(new_lefthand_side,righthand_side))

这应该适用于您提供的类型的不等式。此函数不会简化先验为负或多变量的因素。但我认为这是一个合理的起点