我正在尝试在 sympy 中制定一个分段函数,然后绘制它,但我无法制定想要的函数。问题在于,(x > 0) & (x < 1)
评估x > 0
在传递给分段构造函数之前始终True
。这可以通过在符号构造函数中不设置positive=True
来规避,但这会使平方根简化为√(x^2)
,在这种情况下,我希望它简化为x
。我目前正在Windows上使用最新版本的Anaconda Distribution中的基本(根(环境。该代码在上述环境中使用JupyterLab笔记本进行了测试。
当前代码:
from sympy import *
x = symbols('x', real=True, positive=True)
f = sqrt(x**2)
f_piecewise = Piecewise((2, (x > 0) & (x < 1) ),
( 3 * f, (x > 1) & (x < 2) ),
( -3 * f, (x > 2) & (x < 3)),
(0, True)
)
pprint(f_piecewise)
display(f_piecewise)
plot(f_piecewise, (x, -0.01, 3.01))
当前代码的结果:
⎧ 2 for x < 1
⎪
⎪3⋅x for x > 1 ∧ x < 2
⎨
⎪-3⋅x for x > 2 ∧ x < 3
⎪
⎩ 0 otherwise
乳胶和 matplotlib 输出缺少布尔值
预期产出:
⎧ 2 for x > 0 ∧ x < 1
⎪
⎪3⋅x for x > 1 ∧ x < 2
⎨
⎪-3⋅x for x > 2 ∧ x < 3
⎪
⎩ 0 otherwise
乳胶和马特普图库预期产量
当只使用一个布尔值时,我已经想出了一个解决方法,例如更大的。 错误代码:
test = Piecewise((f, (x > 0)),
(1, True)
)
pprint(test)
display(test)
plot(test)
工作代码:
test = Piecewise((f, Gt(x, 0, evaluate=False)),
(1, True)
)
pprint(test)
display(test)
plot(test)
我已经尝试了以下方法以使其与"和"一起使用,但没有一个起作用:
from sympy.parsing.sympy_parser import parse_expr
test = Piecewise((f, parse_expr("GreaterThan(x, 0, evaluate=False) & (x < 1)", {'x':x}, evaluate=False)),
(1, True)
)
test = Piecewise((f, And(GreaterThan(x, 0, evaluate=False), (x < 1), evaluate=False)),
(1, True)
)
感谢任何人花时间看这个:D。
Sympy 形成了正确的方程组。 关键是您将符号变量设置为正数。在这种情况下,系统:
⎧ 2 for x < 1
⎪
⎪3⋅x for x > 1 ∧ x < 2
⎨
⎪-3⋅x for x > 2 ∧ x < 3
⎪
⎩ 0 otherwise
将是正确的。
要获得预期的系统,您需要删除阳性约束。以下代码有效。
from sympy import *
x = symbols('x', real=True)
f = sqrt(x**2)
f_piecewise = Piecewise((2, (x > 0) & (x < 1) ),
( 3 * f, (x > 1) & (x < 2) ),
( -3 * f, (x > 2) & (x < 3)),
(0, True)
)
pprint(f_piecewise)
这是它返回的内容:
⎧ 2 for x > 0 ∧ x < 1
⎪
⎪3⋅│x│ for x > 1 ∧ x < 2
⎨
⎪-3⋅│x│ for x > 2 ∧ x < 3
⎪
⎩ 0 otherwise
附注:请注意,您的函数在第 1 点和第 2 点定义为零。使用">="或"<="进行正确的行为。不幸的是,这些点在图表上没有反映为 0。