[英]Integrate and plot a piecewise function in Sagemath
我正在尝试使用Sagemath集成一个分段函数,并发现它是不可能的。 我的原始代码如下,但由于此处描述的意外评估,这是错误的。
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)
,但由于TypeError
了TypeError
,因此显然不支持integrate()
函数。
有没有解决这个问题,我不知道?
不是通过def
定义分段函数,而是使用内置的分段类 :
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)。 这不像gg(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)
工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.