在Sympy符号布尔运算

在Sympy符号布尔运算

本文介绍了在Sympy符号布尔运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个符号一个布尔变量的布尔运算产生类型错误,但是反过来也没有问题:

Boolean operation of a Boolean variable on a symbol produces TypeError, but the reverse has no problem:

>>> from sympy import *
>>> x = Symbol('x', bool=True)
>>> x ^ True
Not(x)
>>> True ^ x

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    True ^ x
TypeError: unsupported operand type(s) for ^: 'bool' and 'Symbol'

我能做的try-catch:

I can do try-catch:

try :
    print True ^ x
except TypeError:
    print x ^ True

Not(x)

但是,对于我的present的任务,这是不可能的来实现这一尝试 - 除了,因为我有对付〜200的符号。我怎样才能做到这一点?

But, for my present task, it is impossible to implement this with try-except as I have to deal with ~200 symbols. How can I achieve this?

推荐答案

这是一个错误,它已被固定在SymPy的开发版本,并将在下一版本。如果您无法使用Git版本,不能等待,一个解决方法是猴补丁 __ __ rxor (等)在 sympy.logic .boolalg.Boolean 等于 sympy.logic.boolalg.Boolean .__ XOR __

This is a bug, and it has been fixed in the development version of SymPy, and will be fixed in the next version. If you can't use the git version and can't wait, a workaround would be to monkeypatch __rxor__ (and so on) in sympy.logic.boolalg.Boolean to be equal to sympy.logic.boolalg.Boolean.__xor__.

In [1]: from sympy.logic.boolalg import Boolean

In [2]: Boolean.__rxor__ = Boolean.__xor__

In [3]: True ^ x
Out[3]: ¬ x

顺便说一句,符号('X',布尔= TRUE)什么都不做。它增加的假设 x.is_bool 来的符号,但由于这是不是一个真正的假设,即SymPy知道,它不会做任何事情。

By the way, Symbol('x', bool=True) does nothing. It adds the assumption x.is_bool to the Symbol, but since that isn't a real assumption that SymPy knows about, it doesn't do anything.

这篇关于在Sympy符号布尔运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 04:04