我试图在 sympy 中设置一个条件语句,以便在这种情况下当可迭代不等于某个数字(30)时,它返回 0。
我的代码是:
def formula(address):
address0 = 30
logic = 3 * x
# Define the symbol and the summation range
x = symbols('x')
expr = Piecewise(
(x + logic, logic == address0), # When x equals certain_integer, only add logic
((x + logic) - (x + logic), logic!=address0) # For all other values of x, apply full logic (x + logic - x + logic)
)
#If -x + logic only do it to the ones that aren't address0
total = summation(expr(x, 0, 089237316195423570985008687907836))
total2 = total - address0
print(f'{total}\n{total2}')
return total2
正如您在我的代码中看到的,在 expr 变量中,当逻辑为 30 时,我设置 x+logic,而当其他逻辑不是 30 时,它返回 0,因为它减去了它。无论我做什么,代码都会返回 0,我不知道为什么。有人可以帮助我吗?
==
运算符将根据对象的结构立即评估为True或False。由于 3*x
不是 30
,因此等式计算结果为 False,并且忽略分段项。请改用以下内容:
...
from sympy import Eq
expr = Piecewise(
(x + logic, Eq(logic,address0)),
(0, True)) # (x+logic)-(x-logic)->0 if x and logic are finite
你对
summation
的使用似乎也很奇怪。怎么样:
>>> piecewise_fold(Sum(expr,(x,0,100))).doit()
Piecewise((20200, Eq(x, 10)), (0, True))
但我不太确定你想用求和来做什么。