如何在Sympy 1.3中执行间隔算术? (特别是加法和乘法)
例如,给定:
q1 = Interval(0,255)
q2 = Interval(0,255)
这两个间隔的和应为Interval(0, 510)
。 (加号运算符重载为“ union”,因此q1 + q2产生Interval(0,255)。)
如果我尝试Add(q1, q2)
,则会出现异常:
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
也有类似的例外)。
但是,添加两个时间间隔的代码似乎就在这里:https://github.com/sympy/sympy/blob/sympy-1.3/sympy/sets/handlers/add.py#L22
但是调度程序机制似乎并没有抓住Interval + Interval的情况。
如何在sympy中对间隔进行加法和乘法?
答案 0 :(得分:2)
Sympy间隔不执行间隔算术。您在存储库中找到的函数是.pipe(concat('styles.css', {rebaseUrls: false}))
的处理程序之一,该表达式类型接受给定集合中的值:
sympy.sets.setexpr.SetExpr
from sympy import Interval
from sympy.sets.setexpr import SetExpr
q1 = SetExpr(Interval(0, 255))
q2 = SetExpr(Interval(0, 255))
result = q1 + q2
当前是隐藏的,几乎没有文档。
答案 1 :(得分:1)
除了SetExpr(Interval(...))
之外,您还可以使用较旧的AccumBounds
,其最初目的是为了回答“找到f
的限制”,其中f
是振荡功能。就算术而言,它的工作原理相同:
AccumBounds(3, 5) + AccumBounds(2, 8) # AccumBounds(5, 13)
AccumBounds(-2, 5) * AccumBounds(2, 8) # AccumBounds(-16, 40)
但是在一些间隔计算中,AccumBounds
的实现更加完整。
sin(AccumBounds(0, 3)) # AccumBounds(0, 1)
sin(SetExpr(Interval(0, 3))) # SetExpr(ImageSet(Lambda(x, sin(x)), Interval(0, 3)))