我正在尝试使用 Sagemath 积分分段函数,但发现这是不可能的。我的原始代码如下,但由于here描述的意外评估而出现错误。
def f(x):
if(x < 0):
return 3 * x + 3
else:
return -3 * x + 3
g(x) = integrate(f(t), t, 0, x)
网站上提到的绘图修复方法是使用
f
而不是 f(t)
,但这显然不支持 integrate()
函数,因为会引发 TypeError
。
是否有我不知道的修复方法?
不要通过
def
定义分段函数,而是使用内置的 piecewise 类:
f = Piecewise([[(-infinity, 0), 3*x+3],[(0, infinity), -3*x+3]])
f.integral()
输出:
Piecewise defined function with 2 parts, [[(-Infinity, 0), x |--> 3/2*x^2 + 3*x], [(0, +Infinity), x |--> -3/2*x^2 + 3*x]]
分段函数有自己的方法,例如
.plot()
。不过,绘图不支持无限间隔。可以获得有限间隔的图
f = Piecewise([[(-5, 0), 3*x+3],[(0, 5), -3*x+3]])
g = f.integral()
g.plot()
但是你还想从 g 中减去 g(0)。这不像 g-g(0) 那么简单,但也不算太糟糕:使用
g.list()
获取片段列表,从每个函数中减去 g(0),然后重新组合。
g0 = Piecewise([(piece[0], piece[1] - g(0)) for piece in g.list()])
g0.plot()
你就有了:
通过扩展这种方法,我们甚至不需要从一开始就在 f 中放置有限的区间。以下通过修改定义域在给定区间 [a,b] 上绘制 g - g(0):
a = -2
b = 3
g0 = Piecewise([((max(piece[0][0], a), min(piece[0][1], b)), piece[1] - g(0)) for piece in g.list()])
g.plot()
除了使用 Piecewise 类之外,还可以通过将
g(x)
定义为 Python 函数来轻松解决此问题:
def f(x):
if(x < 0):
return 3 * x + 3
else:
return -3 * x + 3
def g(x):
(y, e) = integral_numerical(f, 0, x)
return y
然后
plot(g)
就可以正常工作了。
在较新的 SageMath 版本中,请使用
piecewise
(小写)。
sage: f = piecewise([((-oo, 0), 1), ((0, 1), 2), ((1, oo), 3)], var=x)
sage: f
piecewise(x|-->1 on (-oo, 0), x|-->2 on (0, 1), x|-->3 on (1, +oo); x)
sage: g = integrate(f, x)
sage: g
piecewise(x|-->x on (-oo, 0), x|-->2*x on (0, 1), x|-->3*x - 1 on (1, +oo); x)
sage: plot(g, (x, -2, 2))
Launched png viewer for Graphics object consisting of 1 graphics primitive
除此之外,您还可以使用
sgn
、abs
和 heaviside
来构建逻辑表达式。
sage: f = heaviside(x)*1 + (1-heaviside(x))*2
sage: f
-heaviside(x) + 2
sage: g = integrate(f, x)
Warning: piecewise indefinite integration does not return a continuous antiderivative
sage: g
-x*heaviside(x) + 2*x
sage: plot(g, (x, -2, 2))
Launched png viewer for Graphics object consisting of 1 graphics primitive
理想情况下,SageMath 可以暴露 Maxima 的
charfun
(https://stackoverflow.com/a/24915794),但目前还没有。 integrate
无论如何,主要依赖 Maxima。