如何在 sympy 1.3 上进行区间算术? [英] How to do interval arithmetic on sympy 1.3?
问题描述
我如何在 Sympy 1.3 中进行区间运算?(特别是加法和乘法)
How do I do interval arithmetic in Sympy 1.3? (specifically, addition and multiplication)
例如,给定:
q1 = Interval(0,255)
q2 = Interval(0,255)
这两个区间的相加应该是Interval(0, 510)
.(加号运算符被重载为联合",因此 q1+q2 产生 Interval(0,255).)
The addition of those two intervals should be Interval(0, 510)
. (The plus operator is overloaded to mean "union", so q1+q2 yields Interval(0,255).)
如果我尝试 Add(q1, q2)
,我会得到一个异常:
If I try Add(q1, q2)
, I get an exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/sympy/core/compatibility.py", line 850, in wrapper
result = user_function(*args, **kwds)
File "/usr/local/lib/python2.7/dist-packages/sympy/core/operations.py", line 45, in __new__
c_part, nc_part, order_symbols = cls.flatten(args)
File "/usr/local/lib/python2.7/dist-packages/sympy/core/add.py", line 223, in flatten
newseq.append(Mul(c, s))
File "/usr/local/lib/python2.7/dist-packages/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/sympy/core/compatibility.py", line 850, in wrapper
result = user_function(*args, **kwds)
File "/usr/local/lib/python2.7/dist-packages/sympy/core/operations.py", line 45, in __new__
c_part, nc_part, order_symbols = cls.flatten(args)
File "/usr/local/lib/python2.7/dist-packages/sympy/core/mul.py", line 186, in flatten
r, b = b.as_coeff_Mul()
AttributeError: 'Interval' object has no attribute 'as_coeff_Mul'
(Mul
也有类似的异常).
(I get a similar exception for Mul
).
然而,添加两个间隔的代码似乎就在这里:https://github.com/sympy/sympy/blob/sympy-1.3/sympy/sets/handlers/add.py#L22
Yet, the code to add two intervals seems to be right here: https://github.com/sympy/sympy/blob/sympy-1.3/sympy/sets/handlers/add.py#L22
但是调度器机制似乎没有捕捉到 Interval + Interval 的情况.
But the dispatcher mechanism doesn't seem to be catching the case of Interval + Interval.
如何在 sympy 中对间隔进行加法和乘法?
How do I do addition and multiplication on intervals in sympy?
推荐答案
Sympy Intervals 不执行区间算术.您在存储库中找到的函数是 sympy.sets.setexpr.SetExpr
的处理程序之一,这是一种采用给定集合中的值的表达式类型:
Sympy Intervals do not perform interval arithmetic. The function you found in the repository is one of the handlers for sympy.sets.setexpr.SetExpr
, an expression type that takes values in a given set:
from sympy import Interval
from sympy.sets.setexpr import SetExpr
q1 = SetExpr(Interval(0, 255))
q2 = SetExpr(Interval(0, 255))
result = q1 + q2
SetExpr
目前是隐藏的,而且大部分都没有记录.
SetExpr
is currently hidden-ish and mostly undocumented.
这篇关于如何在 sympy 1.3 上进行区间算术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!